How to post various custom data types using Ajax in MVC3?
-
25-06-2021 - |
Question
I have this ViewModel to represent each Category and it's several Sub-Categories in my project:
public class Categories
{
//a simple string for the category name
[Required]
public string Cat_Name { get; set; }
//a list of strings for the sub-categories
public List<string> SubCat_Name { get; set; }
}
I pass this model to the view, and I use it to construct my form like this:
@using (Html.BeginForm("Category", "Admin", FormMethod.Post))
{
@Html.TextBoxFor(m => m.Name, new { @class = "Cat" })
@Html.TextBoxFor(m => m.SubName, new { @class = "Sub" })
@Html.TextBoxFor(m => m.SubName, new { @class = "Sub" })
@Html.TextBoxFor(m => m.SubName, new { @class = "Sub" })
@Html.TextBoxFor(m => m.SubName, new { @class = "Sub" })
<input type="button" value="Create New Category" name="Category" onclick="DoIt()" />
}
And as you see, the javascript function "DoIt()
" is called by the click on the input button.
here's the function :
function DoIt() {
var stringArray = new Array();
//I put all of the sub-categories inside an array, to be like a list<string>
$(".Sub").each(function (index, value) {
stringArray[index] = this.value;
});
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify($(".Cat").attr("value") , stringArray),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("post done"); },
error: function () { }
});
}
As you can see, in the ajax method I'm trying to pass the "Category Name" $(".Cat").attr("value")
and it's "Sub-Category Names" stringArray
to the corresponding action method which requires Categories
datatype I created as a viewmodel before. It looks like this:
public ActionResult Category(Categories CAT)
{
//Do something
return View();
}
The problem is the ajax method can't post two datatypes at once, or just that I don't know how to do it.
I also tried this :
var postdata = {
Name: $(".Cat").attr("value"),
SubName: stringArray
};
and put postdata
inside the JSON.stringify()
instead. But still nothing is passed to the action method.
Solution
I think you are very close.
Try this
var postdata = {
Cat_Name: $(".Cat").val(),
SubCat_Name: stringArray
};
&
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify(CAT:postdata),
dataType: "json",
contentType: "application/json",
success: function () { console.log("post done"); },
error: function () { }
});
OTHER TIPS
Try to send data formatted like this:
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify({ Cat_Name: $(".Cat").val(), SubCat_Name: stringArray }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("post done"); },
error: function () { }
});