How to display “Message box” using MVC3 controller

2020-04-24 10:56发布

问题:

I have been facing an issue to display "Message Box" after executing of some code in controller

for ex:-

public ActionResult IsLoginExsit(CustomerDO loginData)
        {

            JsonResult jsonResult = new JsonResult();            
             if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty(loginData.Password))                 
             {                     
                 bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password);                     

                     jsonResult.Data = result;

             }      
             return jsonResult;
        }

as seen in above example, if result is true or false, then i would like to display message box stating that login is suceess or fail.

<!-- language: lang-.html -->
    <form class="formStyle" action="#" method="POST" id="frmAuthenticate">
            <div class="row">
            <input class="text row" type="text" value="" id="txtUserName"/>
            </div>
            <div class="row">
            <input class="text row" type="password" value="" id="txtPassword" /> 
            </div>  
            <div class="row last">
            <a class="link" href="">Forgot Password?</a>   
            <a class="button3" href="/Registration/Registration" title="Registration" >Signup</a>        
<input type="submit" class="button4" id="btnGo" value="Go" />            
            </div>
        </form>

If login is exist i want to navigate to "/Customer/CollaborationPortal", else i would like to display message "Authroization fail".

$("#btnGo").click(function (e) {
                var RegData = getRegData();
                if (RegData === null) {
                    console.log("Specify Data!");
                    return;
                }
 var json = JSON.stringify(RegData)
                $.ajax({
                    url: '/Registration/IsLoginExsit',
                    type: 'POST',
                    dataType: 'json',
                    data: json,
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {                     
                    if(data.result == true){                                                 
                    location.href = "/Customer/CollaborationPortal";                     
                    }                    
                     else{
                         alert("Login failed"); //or whatever                     
                     }             
                     }
                });
return false;
            });
            function getRegData() {

                var UserName = $("#txtUserName").val();
                var Password = $("#txtPassword").val();
                return { "UserName": UserName, "Password": Password };
            }

Thanks in advance

回答1:

There is no way do that in MVC as simple as in winforms application.

Simplest way to display message box on web page in your case is to change this action from ActionResult to JsonResult, and replace your if with:

return Json(new {result = result});

and, in web page you need to use ajax (i.e. submit a form using jquery's $.post) and in callback function check for result:

$("form input[type=submit]").click(function(){
    var formData = $(this).closest("form").serialize();
    $.post("urltoyourcontrollerhere/IsLoginExsit", formData, function(data){
        if(data && data.result == true){ alert("Login exists!");}
    });
});

UPDATE The code you posted seems OK, but there is one problem. The success function:

success: function (data) {
                        location.href = "/Customer/CollaborationPortal";
                    }

This function will always perform redirect, no matter what controller has returned. You need to check if data.result (if you returned your json as Json(new {result = result});) is true, and then redirect, else display alert. So, try:

success: function (data) {
                    if(data.result == true){                        
                        location.href = "/Customer/CollaborationPortal";
                    }
                    else{
                        alert("Login failed"); //or whatever
                    }
            }

Another thing:

            var RegData = getRegData();
            if (RegData === null)

If you want this to work, you need to return null from getRegData when one of textboxes is empty.



回答2:

You CAN display a message box when done.

public ActionResult LoginExist(BAMasterCustomerDO loginData)
{
    return new JavascriptResult { Script = "alert('Saved successfully');" };
}


回答3:

You won't be able to display a message box using the server side code. You'll need to pass some data back to the view indicating the login status then write some client side code to display the message box.



回答4:

You could use a property of your view model which will be passed to the view and which will contain this information:

var model = new MyViewModel();
bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password);
model.IsLoginSuccess = result;

... 

return View(model);

and inside your strongly typed view you would test the value of this property and display the message accordingly:

@if (Model.IsLoginSuccess)
{
    <div>The Login was successful</div>
}