Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post viewmodel in MVC using jquery [closed]

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); }
                });
like image 672
user3711357 Avatar asked Aug 03 '14 16:08

user3711357


2 Answers

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
});
like image 78
Viktor Bahtev Avatar answered Nov 17 '22 22:11

Viktor Bahtev


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.

like image 2
Kundan Singh Chouhan Avatar answered Nov 17 '22 21:11

Kundan Singh Chouhan