How to post the viewmodel to action method using J

2019-02-21 00:24发布

问题:

I want to achieve create (INSERT) screen using $.POST or $.AJAX.

Note: code is working fine without AJAX call..it is already there.. now i need to do ajax call and save without postback. I wrote below code:

On submit click event following is the code:

$.ajax(
      {
          url: '@Url.Action("CreateProduct","ProductManagement")',
          dataType: 'json',
          contentType: 'application/json; charset=utf-8',
          type: 'post',
          data:   $('frm').serialize(),
          success: function () { alert('s'); },
          error: function (e1, e2, e3) { alert(e2); alert(e1 + ' ' + e2 + ' ' + e3); alert('failure event'); }
      }
    );
});

On server side:

[HttpPost]
public JsonResult CreateProduct(FormCollection frm)
{
    manager.ProductManager m = new manager.ProductManager();
    // m.InsertProduct(new common.DTO.ProductDTO() { Id = id, ProductName = ProductName, Description = Description, Cost = cost, ProductTypeId = 5 });
    return Json("'result':'success'", JsonRequestBehavior.AllowGet);
}

Problem is , every time, it call the action but no data found on frm argument param. i also tried to keep as - View model ProductViewModel vm as argument but it did not work..just giving me null value. also, in ajax call, it goes in success but. just problem is nothing posted on controller's action.

Html is as follow:

  @using (Html.BeginForm("CreateProduct", "ProductManagement", FormMethod.Post, new { id = "frm" }))
    {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>ProductViewModel</legend>
    <div id="CreateDiv">
        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Cost)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Cost)
            @Html.ValidationMessageFor(model => model.Cost)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductTypeId)
        </div>
        <div class="editor-field">
            @Html.DropDownList("ProductTypeId", "Choose item")
            @Html.ValidationMessageFor(model => model.ProductTypeId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductTypeName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductTypeName)
            @Html.ValidationMessageFor(model => model.ProductTypeName)
        </div>
    </div>
    <p>
        <input type="submit" value="Create" id="btnSubmit" />
    </p>

</fieldset>
 }

 <div>
 @Html.ActionLink("Back to List", "Index")
 </div>

Please guide me what is wrong here.

Thank You

回答1:

For id Selector you have to use "#" with id.

This will work :

$.ajax(
  {
      url: '@Url.Action("CreateProduct","ProductManagement")',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      type: 'post',
      data:   $('this').serialize(), OR  $('#frm').serialize(),   <-----------------
      success: function () { alert('s'); },
      error: function (e1, e2, e3) { alert(e2); alert(e1 + ' ' + e2 + ' ' + e3); alert('failure event'); }
  }
 );

OR Try this :

var form = $('#frm');
$.ajax({
 cache: false,
 async: true,
 dataType: 'json',
 contentType: 'application/json; charset=utf-8',
 type: "POST",
 url: form.attr('action'),
 data: form.serialize(),
 success: function (data) {
 alert(data);
   }
 });


回答2:

You have forgot to add id selecter:

$.ajax(
      {
          url: '@Url.Action("CreateProduct","ProductManagement")',
          dataType: 'json',
          contentType: 'application/json; charset=utf-8',
          type: 'post',
          data:   $('#frm').serialize(),                      // $('#frm');
          success: function () { alert('s'); },
          error: function (e1, e2, e3) { alert(e2); alert(e1 + ' ' + e2 + ' ' + e3); alert('failure event'); }
      }
    );


回答3:

If the id of your form is frm, then it should be referenced as follows

data:   $("#frm").serialize(),