K.Z
K.Z

Reputation: 5075

asp.net-mvc send json response to view in ajax function along with ablity to send partial view or model data in json format

I have actionResult method in controller which is been called via ajax javascript function which display form. This partial view appears in web page along with other part in div with class="webPage_content_block". Now I am require to do the server validation for form field, in case any of field incorrect, partial view is pass along with model, but where my issue is in ajax function. what I want if everything is ok in form, controller pass json message return Json(new { Response = "Success" }) and in ajax done method if I get success then redirect to different page i.e. view else alert message

[HttpGet]
public ActionResult CreateNewFunctionNavigation()
  {
        return PartialView("CreateNewNavigation_Partial");
  }

[HttpPost]
public ActionResult CreateNewFunctionNavigation(CreateFunctionNavigation_SP_Map obj )
    {
        if(ModelState.IsValid)
        {
            try
            {
                 _FN_Services_a2.CreateFunctionNavigation(obj);

                 return Json(new { Response = "Success" });   
            }
            catch (DataException ex)
            {
                ModelState.AddModelError("", "Unable To Create New Function Navigation" + ex);
            }
        }
        return PartialView("CreateNewNavigation_Partial", obj);

    } //end

ajax

$('#NewFunctionNavigationForm').submit(function (e) {
   e.preventDefault();

  $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
    }).done(function (result) {
        $('.webPage_content_block').html(result);
    });
 });

razor form

 @using (Html.BeginForm("CreateNewFunctionNavigation", "SystemCore", FormMethod.Post, new { id = "NewFunctionNavigationForm" }))
    {
            @Html.AntiForgeryToken()

            @Html.ValidationSummary(true)
     //form fields here....
<div class="form-group">
     <div class="col-md-offset-2 col-md-10">
          <input type="submit" value="Create" class="btn btn-default _formButton" />
           <input type="button" value="Cancel" class="btn btn-default _formButton" onclick="CancelPage();" />
       </div>
</div>
}

Upvotes: 0

Views: 2333

Answers (1)

Shyju
Shyju

Reputation: 218702

Since you are making an asynchronous request to save data,i would recommend returning JSON response in the case of success and failure. If your form is not properly filled (ModelValidation failed), then you should return a json data structure which has the validation errors and show the errors in the UI.

[HttpPost]
public ActionResult CreateNewFunctionNavigation(CreateFunctionNavigation_SP model)
{
    if (ModelState.IsValid)
    {
       //Validation passed, Save data or do soemthing
        return Json(new { IsSuccess = true });
    }
    else
    {
        //Validation failed. Let's get the error messages

        var errors =  ModelState.Select(x => x.Value.Errors)
                    .Where(y => y.Count > 0).ToList();
        var errorList=new List<string>();
        foreach (var err in errors)
        {
            errorList.AddRange(err.Select(errItem => errItem.ErrorMessage));
        }
        return Json(new { IsSuccess=false,Errors=errorList});
    }
}

Also, Add an element to your UI to show the errors.

 <ul id="clientErrors"></ul>
 @using (Html.BeginForm())
 {
    //your form elements to capture user input

    <input id="btnGo" type="submit" value="Go" />
 }

and your script to handle the form posting is

$(function () {

    $("#btnGo").click(function (e) {
        e.preventDefault();

        var _form = $(this).closest("form");
        var _formData = _form.serialize();


        $.post(_form.attr("action"), _formData, function (res) {

            if (!res.IsSuccess) {
                var errors = "";
                $.each(res.Errors, function(i,item) {
                    errors = errors +"<li>"+ item+"</li>";
                });
                $("#clientErrors").html(errors);
            }
            else
            {
               //No errors. May be redirect ?
            }
        });      

    });

});

Upvotes: 0

Related Questions