Question

is it possible to load the modelstate errors a 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*/ }                
});
Was it helpful?

Solution 2

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!

OTHER TIPS

I've solved today this problem, with something like this

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

and

$.ajax({
   type: 'POST',
   url: '/Receipt/Create',
   cache: false,
   data: $("#CreateForm").serialize(),
   success: function (e) { 
if(e.Valid){
    window.location="/Controller/Action";}
else{
    return false;
  } },
   error: function (e) { e.preventDefault();$("#mymodal").load(e) } 
 });

it is something like jmrnet said. Thanks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top