0

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>
}
4

1 回答 1

0

由于您正在发出异步请求以保存数据,因此我建议在成功和失败的情况下返回 JSON 响应。如果您的表单未正确填写(ModelValidation 失败),那么您应该返回一个包含验证错误的 json 数据结构并在 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});
    }
}

此外,向您的 UI 添加一个元素以显示错误。

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

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

并且您处理表单发布的脚本是

$(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 ?
            }
        });      

    });

});
于 2015-04-15T14:00:09.327 回答