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

3
  • On server side code you forgot to provide attribute named - [HTTPPost] no CreateProduct() method. Commented Aug 3, 2014 at 13:26
  • its der.. forgot to post.apologies. updated above code. Commented Aug 3, 2014 at 13:28
  • @user3711357...now getting form values??? Commented Aug 3, 2014 at 13:46

3 Answers 3

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);
   }
 });
Sign up to request clarification or add additional context in comments.

8 Comments

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.
hey try this alert($('#ProductName').val()); you re not using #
oh sorry... got the alert for correct value. but, no data posted on formcollection and it just give me count 0.
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..
|
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'); }
      }
    );

Comments

0

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

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

8 Comments

when I first started the response you hadn't put the htlm. It was as I suspected, the above change will fix the problem.
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.
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.
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' :)
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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.