How to post viewmodel in MVC using jquery
Solution 1
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
});
Solution 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.
user3711357
Updated on July 09, 2022Comments
-
user3711357 almost 2 years
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); } });
-
user3711357 almost 10 yearsadded 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. -
Kundan Singh Chouhan almost 10 years@user3711357, is it going to controller's action method? did you debug that over there? Have a look on that first.
-
user3711357 almost 10 yearsthank 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 asreturn 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.? -
user3711357 almost 10 yearsyes, it goes to server but, returning into error result.. just succeed now, as posted in above answered comment.
-
Kundan Singh Chouhan almost 10 years@user3711357, as he suggested that it's automatically so you do not need to define it.
-
user3711357 almost 10 yearsya, 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..
-
user3711357 almost 10 yearsgot solution for solution about notification message at- stackoverflow.com/questions/6114360/… Thank You.