5

How do I do an ajax call with jQuery so that I can use $.ajax to post the ViewModel to controller's action method?

I have not used the Form element because, I don't want postback...

My form looks like this so far:

HTML:

  @model comp.learn.data.Models.ProductViewModel

 @{
ViewBag.Title = "Create";
}

 <h2>Create</h2>


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

jQuery/JavaScript:

         $.ajax(
                {
                    url: '@Url.Action("CreateProduct","ProductManagement")',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    type: 'post',
                    cache: false,
                    data: ///what should i write here ,
                    success: function (data) { alert('final'); },
                    error: function (f1, f2, f3) { alert(f3); }
                });
2
  • Passing the form will not cause full page post back. Look over the pattern to what solved a similar StackOverflow question (here is the link) a few hours ago, it combines both of the answers provided below: 1) giving a clear example on how to use beginform and how to serialize the data going to the action. I personally usually use json.Stringify (example in the answer provided below by @Viktor Bahtev). Commented Aug 3, 2014 at 17:01
  • i need to write, e.preventDefaultAction on button click, which avoied it. plz dont make down vote.. it beahves like that so.. wrote. Commented Aug 3, 2014 at 17:04

2 Answers 2

14

You should collect the data from inputs manually and construct JSON object that correspond to your C# model class. For example if you wait ProductViewModel object in your action method you can follow this example:

var myData = {
    productName: $('#ProductName').val(),
    cost: $('#Cost').val(),
    // .. and so on
};

$.ajax({
    data: JSON.stringify(myData),
    // .. the other ajax options
});

It's even easier if you have form element. Just select the form with jQuery and call serialize method. The data will be encoded as a string for submission. The format will be application/x-www-form-urlencoded; charset=UTF-8 that is the $.ajax default too and you won't need to specified it. Example:

var myData = $('#myFormId').serialize();
$.ajax({
    data: myData,
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    //..Other ajax options
});
Sign up to request clarification or add additional context in comments.

2 Comments

thank you sir. i tried many option and not succeed.. your suggested contentType: 'application/x-www-form-urlencoded; charset=UTF-8', option made me success. :). just one question, now, when result return form action json result as return Json(new { val = "success" }, JsonRequestBehavior.AllowGet); in IE, it shows me browser notification as , do you want to open or save Createproduct7878(17 byte) from location ? message... is it correct behaviour of ajax where returing json from controller's action.?
got solution for solution about notification message at- stackoverflow.com/questions/6114360/… Thank You.
2

You would require two things to achieve this:

First: Wrap all the input/data elements of your in form tag view like below:

@using(Html.BeginForm())
{
    //exitsing html stuff
}

Second: In Ajax request use serializeArray() to encode a set of form elements and pass it in data like below:

$.ajax(
{
    url: '@Url.Action("CreateProduct","ProductManagement")',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    type: 'post',
    cache: false,
    data: $('form').serializeArray(),
    success: function (data) { alert('final'); },
    error: function (f1, f2, f3) { alert(f3); }
});

This will fix your concern.

5 Comments

added form tag. it able to post data to server in viewmodel. but problem is, it responded into error callback and not into success.. giving error as internal server error. also, in browser, got notification as Do you want to open or save CreateProduct78545.json(17 byte) from localhost? please tell me how to resolve.
@user3711357, is it going to controller's action method? did you debug that over there? Have a look on that first.
yes, it goes to server but, returning into error result.. just succeed now, as posted in above answered comment.
@user3711357, as he suggested that it's automatically so you do not need to define it.
ya, but, if i don't specify then, it did not work and goes to error for my case. when i specify then only worked. even, i do struglling since 3 hours..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.