Ajax.BeginForm Handling two different answers onSuccess, MVC 5, C #

I am new to Ajax and JQuery, so I need you to forgive me if I try to do something stupid, I work with MVC 5 and Ajax.Beginform, and what I'm trying to do is have an ajax form, I I need to test it using jquery unobtrusive, if I get the correct jQuery validation work with ModelState and return the view again if a validation error is detected, in this case I need to update my form so that the validation message appears in the user's browser, for example, here is my controller:

[HttpPost]
public ActionResult Index(AddProduct model)
{
    if (ModelState.IsValid)
    {
        // connect to the database save data etc... 
        return PartialView("~/Views/Shared/_MyModal.cshtml");
    }
    else
    {
        return View(model);
    }
}

ModelState.IsValid (Bootstrap Modal), , ,   , , TargetId ajax, ajax , ajax:

<div id="result">
 @using (Ajax.BeginForm("Index", new AjaxOptions
  {
      InsertionMode = InsertionMode.Replace,
      UpdateTargetId = "result",
      HttpMethod = "POST",
      OnBegin = "onBegin();",
      OnComplete = "onCompleated();",
      OnSuccess = "onSuccess()",
      OnFailure = "onFailure()"
 }))
 {
@Html.ValidationSummary(true)
<div id="form1" class="form-horizontal">
    <div class="row">
        <div class="form-group">
            @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.Name, new { @class = "form-control"       })
                @Html.ValidationMessageFor(m => m.Name, String.Empty, new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Price, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.Price, new { @class = "form-control" })
                @Html.ValidationMessageFor(m => m.Price, String.Empty, new { @class = "form-help form-help-msg text-red" })
            </div>
        </div>

        <div class="form-group">
            <button class="btn btn-default col-md-2 col-md-offset-2" type="submit">Save &nbsp;&nbsp;</button>
        </div>
    </div>
</div>
 }
  </div>

else Bootstrap Modal, ajax. Modal, ModelState. IsValid . onSuccess ajax. , , javascript onsuccess():

function onSuccess() {
    $('#myModal').modal('hide')
    $("#resultModal").modal({
        backdrop: 'static',
        keyboard: false
    });
    $('#resultModal').on('hidden.bs.modal', function (e) {
        window.location = "/product";
    });
}

$(# 'myModal'). modal ('hide') - . , Modal, , Posting , :

  • , UpdatetargetId ajax, , Exist, , , , , - , , ModelStat, , , , , .

  • , onSuccess() Mehtod, , , . Modal Index, , , , - , .

, Advance,

+4
1

, , .

, onSuccess , , ModelState , . [HttpPost] :

 [HttpPost]
        public ActionResult Index(AddProduct model)
        {
            if (ModelState.IsValid)

            {
                return Json(new {isValid = true, data = this.RenderPartialViewToString("ViewWhenModelStasteIsValid",model,false)});
            }
            else
            {
                return Json(new { isValid = false, data = this.RenderPartialViewToString("ViewWhenModelStasteIsNotValid", model, false) });
            }
        }

public static string RenderPartialViewToString(this Controller controller, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

            }
            controller.ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

UpdateTargetId .

, onSuccess

function onSuccess(result, ref) {
         if (result.isValid) {
           jQuery("#result).html(result.data);
          } else {
            jQuery("#form1").html(result.data);
        }
    }

onSuccess, OnSuccess = "onSuccess()" OnSuccess = "onSuccess (, )" .

, :

@using (Ajax.BeginForm("Index", new AjaxOptions
  {
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnBegin = "onBegin();",
OnComplete = "onCompleated();",
OnSuccess = "onSuccess(data,this)",
OnFailure = "onFailure()"
 }))

, , .

+2

Source: https://habr.com/ru/post/1660691/


All Articles