Binding, posting to a Dictionary in MVC 3 using jQuery ajax
[HttpPost]
public
ActionResult Binding_posting_to_a_dictionary_using_ajax(Dictionary<
string
, UserModel> userList)
{
return
PartialView(
"Success"
);
}
<input name="[0].key" value="firstkey" type="hidden"> <input name="[0].value.FirstName" value="" type="text"> <input name="[0].value.LastName" value="" type="text"> <input name="[0].value.Age" value="" type="text">
If we see the above code block, we can see there is a hidden field for maintaining the key of the dictionary element and the value of the hidden filed is nothing but the key of the dictionary element
<
div
class
=
"data"
>
<
h4
>
First User</
h4
>
<
input
type
=
"hidden"
name
=
"[0].key"
value
=
"first"
/>
First Name: @Html.TextBox("[0].value.FirstName")
Last Name: @Html.TextBox("[0].value.LastName")
Age: @Html.TextBox("[0].value.Age")
</
div
>
<
div
class
=
"data"
>
<
h4
>
Second User</
h4
>
<
input
type
=
"hidden"
name
=
"[1].key"
value
=
"second"
/>
First Name: @Html.TextBox("[1].value.FirstName")
Last Name: @Html.TextBox("[1].value.LastName")
Age: @Html.TextBox("[1].value.Age")
</
div
>
<
div
class
=
"data"
>
<
h4
>
Third User</
h4
>
<
input
type
=
"hidden"
name
=
"[2].key"
value
=
"third"
/>
First Name: @Html.TextBox("[2].value.FirstName")
Last Name: @Html.TextBox("[2].value.LastName")
Age: @Html.TextBox("[2].value.Age")
</
div
>
<
input
type
=
"button"
id
=
"submitData"
value
=
"Submit data"
/>
<
script
type
=
"text/javascript"
>
$(document).ready(function () {
$("#submitData").click(function () {
var datatopost = new Object();
$(".data").each(function (i, item) {
datatopost[$(item).find("input[name*=FirstName]").attr("name")] = $(item).find("input[name*=FirstName]").val();
datatopost[$(item).find("input[name*=LastName]").attr("name")] = $(item).find("input[name*=LastName]").val();
datatopost[$(item).find("input[name*=Age]").attr("name")] = $(item).find("input[name*=Age]").val();
datatopost[$(item).find("input[name*=key]").attr("name")] = $(item).find("input[name*=key]").val();
});
$.ajax({
url: '@Url.Action("Binding_posting_to_a_dictionary_using_ajax")',
type: 'POST',
traditional: true,
data: datatopost,
dataType: "json",
success: function (response) {
alert(response);
},
error: function (xhr) {
alert(xhr);
}
});
});
});
</
script
>