jqueryajaxasp.net-mvc-3unobtrusive-javascriptajax.beginform

jQuery.Ajax vs Ajax.beginform with unobtrusive JavaScript


First post, please be gentle :)

I am relatively new to MVC3 and am building a webapp at work.

I have several pages with CheckBoxes that turn features on/off and when they change I submit via a jQuery Ajax call and return a json success/fail to me so I can display a message.

I have some forms with a bunch of fields that I was just submitting (not with Ajax) and checking if the modelstate is valid etc.. and redisplaying the form with messages if not. I want to do this using Ajax instead.

I have a form using Ajax.BeginForm which submits properly to the controller, the model is validated and if it has errors, i return a partial view which is replaced using the UpdateTargetId.

The thing I want to do is this... If the model was valid and the save successful, I need to return a partial view nonetheless because the UpdateTargetId will replace my form no matter what. I would like to send back a 'success' flag of some kind so I can then display a message to say 'your data was saved' or something.

OnSuccess fires if the Ajax call was successful, and doesn't care if the model was valid.

I could use jQuery.Ajax to submit the form and in the controller return the return the PartialView as well as a success or fail I think?

Can anyone tell be what the best practices are when building 'Ajax' web apps?


Solution

  • You may use plain javascript instead of using the Ajax.Beginform helper method to handle this.

    @model ProductViewModel
    <div id="divForm">
    @using(Html.Beginform())
    {
      @Html.TextBoxFor(x=>x.Name)
      @Html.TextBoxFor(x=>x.Location)
      <input type="submit" id="btnSave" />
    }
    </div>
    <div id="divItem" />
    <script type="text/javascript">
      $(function(){
        $("#btnSave").click(function(e){
             e.preventDefault();   // prevent the default form submit
    
             var form=$(this).closest("form");
             $.post(form.attr("action"),form.serialize(),function(result){
                if(result.Status=="success")
                {
                  //show message and load the new partial view if needed.
                  $(#divForm").hide();
                  $("#divItem").html(reuslt.ViewHTML);
                }
                else
                {
                   alert("Error");
                }
             });
        });
      });
    </script>
    

    Assuming you have an HttpPost action method which accepts our form subimt and return JSON data back.

    [HttpPost]
    public ActionResult Edit(ProductViewModel model)
    {
      // here you may validate the model and save if needed and return JSON back.
      //to do  : return JSON
    }
    

    Response JSON should be in the below format.

    { "Status" : "success", "ViewHTML" : "<p>This is some markup</p>" }
    

    This answer explains how to return ViewResult in JSON response.