0

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

Sebastian Krysmanski
  • 8,114
  • 10
  • 49
  • 91
user3711357
  • 1,425
  • 7
  • 32
  • 54

3 Answers3

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);
   }
 });
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
  • ok, tried but ,though no result... `frm.AllKeys.Count()` gives me `0` count value and no data posted. even, on view also, when i do `alert($('ProductName').val());` then it also give me undefined value. not understand what is wrong.. all worked fine without ajax. – user3711357 Aug 03 '14 at 13:47
  • hey try this alert($('#ProductName').val()); you re not using # – Kartikeya Khosla Aug 03 '14 at 13:49
  • oh sorry... got the alert for correct value. but, no data posted on formcollection and it just give me count 0. – user3711357 Aug 03 '14 at 13:53
  • Now, i got the alert when i put `alert($('#frm').serialize)` and it shows serialize data. Now, this line `data: $('#frm').serialize(),` does not work..it gives me error alert as `internal server error` and not able to reach at action method.. – user3711357 Aug 03 '14 at 14:19
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58570/discussion-between-user3711357-and-exception). – user3711357 Aug 03 '14 at 14:24
  • then there is a problem with path just check in browser console the path generated for request??? – Kartikeya Khosla Aug 03 '14 at 14:25
  • I have changed the stuff as data: JSON.stringify({ 'f': $('#frm').serialize() }), [HttpPost] public JsonResult CreateProduct(ProductViewModel f)` able to get call the action but, f remains null only... not understand what is wrong to post the data.. – user3711357 Aug 03 '14 at 14:29
  • try this :data: { modelval: JSON.stringify($('#frm')) } [HttpPost] public JsonResult CreateProduct(ProductViewModel modelval)` – Kartikeya Khosla Aug 03 '14 at 14:36
0

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'); }
      }
    );
AmanVirdi
  • 1,667
  • 2
  • 22
  • 32
0

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

data:   $("#frm").serialize(),
Cindy
  • 26
  • 3
  • when I first started the response you hadn't put the htlm. It was as I suspected, the above change *will* fix the problem. – Cindy Aug 03 '14 at 13:48
  • If you see that your answer becomes outdated then you can edit it at any time. This is better than adding a comment to explain why your answer no longer matches to the information provided by the OP. – honk Aug 03 '14 at 14:00
  • thanks for the tip. from my score you can see I just started. I normally just read answers. I'll get the hang of it. – Cindy Aug 03 '14 at 14:10
  • You are welcome. I reviewed your first post. This is why gave you that tip ;) You can still improve your post by wrapping frm with \` instead of '. And 'references' should be 'referenced' :) – honk Aug 03 '14 at 14:18
  • Can you show me what you mean? I can't quite visualize that. If you add the text instead of to the code, wouldn't it make it more difficult to read? – Cindy Aug 04 '14 at 14:31
  • I mean the following: You wrote "...form is 'frm', then it...". Here you could write "...form is \`frm\`, then it..." which will format `frm` as code. This is appropriate for variable names, etc. – honk Aug 04 '14 at 19:11
  • oh, I get it! the accent mark ` instead of the single quote ' I thought you meant inside the code block. Cool I didn't know I could do that. Thanks. – Cindy Aug 05 '14 at 21:02
  • Again you are welcome :) If you are interested in some more tips then you can have a look at http://stackoverflow.com/editing-help. – honk Aug 06 '14 at 15:45