Search code examples
c#javascriptasp.net-mvcmodal-dialogmodelstate

How to load model errors into modal dialog


is it possible to load the modelstate errors to the same modal dialog after submitting a form with javascript?

My code is something like this:

Controller:

public ActionResult Create(MyModel model){
     if(ModelState.isValid){
           // DB Save
           return RedirectToAction("Index");
     }
     else{
           return View(model);
     }
}

Ajax Method

$.ajax({
       type: 'POST',
       url: '/Receipt/Create',
       cache: false,
       data: $("#CreateForm").serialize(),
       success: function (e) { window.location="/Controller/Action"; },
       error: function (e) { e.preventDefault(); /*Code here to load model error into page*/ }                
});

Solution

  • I was able to accomplish this by using Ajax.BeginForm method with an UpdateTargetId AjaxOption. Here is the code I used. It doesnt exactly fit what you are doing, but it should point you in the right direction.

    In the View:

    @using (Ajax.BeginForm(new AjaxOptions(){ UpdateTargetId="loginresult" }))
    {
        <b>User:</b><br />
        @Html.TextBoxFor(m => m.UserName)<br />
        <br />
        <b>Password:</b><br />
        @Html.PasswordFor(m => m.Password)<br />
        <div id="loginresult"><br /></div>
        <input id="Button1" type="submit" value="Login" class="touch-button" />
    }
    

    In the Controller:

    [HttpPost]
    public ActionResult Index(LoginModel model)
    {
        //Execute Log-in code.
        //Capture any errors and put them in the model.LoginResponse property.
    
        return PartialView("LoginResult", model);
    }
    

    In the LoginResult partial view:

    @model MerchantMobile.Models.LoginModel
    
    @if (String.IsNullOrEmpty(Model.LoginResponse))
    {
        Html.RenderPartial("_AjaxRedirect", Url.Content("~/Home/Activity"));
    }
    else
    {
        <div id="loginresult">
            <div style="color: Red; font-weight: bold;">
                @Model.LoginResponse
            </div>
        </div>
    }
    

    You could easily replace the loginresult <div> with one used by jquery ui to pop up a modal dialog box rather than just show some text in the div.

    Hope this helps!