I have a checkbox list and dropdown list. I want to pass selected value from dropdownlist and checked checkboxes to my MVC3 Controller and use model binding.
ViewModel for checkbox:
public class StateViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
public IEnumerable<TransitionViewModel> Transitions { get; set; }
}
Editor template for StateViewModel /Views/Home/EditorTemplates/StateViewModel.cshtml
:
@model Mcs.Sibs.UI.Web.Models.StateViewModel
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
<div>
@Html.CheckBoxFor(x => x.Checked)
@Html.LabelFor(x => x.Checked, Model.Name)
</div>
My view:
@using (Html.BeginForm("GetSchedules", "Home", FormMethod.Post, new { id = "checkboxFrm" }))
{
@Html.EditorForModel()
<input id="ShowReportScheduleBtn" type="button" value="Show schedule" onclick="ShowReportSchedules()" />
}
Button click handler which is sending data to controller:
function ShowReportSchedules() {
var selectedGenerationId = $('#SelectedGenerationId').val();
var statesData = JSON.stringify($('#checkboxFrm'));
var statesData2 = $('#checkboxFrm').serialize(); //I also tried this
$.ajax({
type: 'POST',
url: '/Home/GetSchedules',
data: { "generationId": selectedGenerationId, "state开发者_如何学Gos": statesData },
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
};
Finally, my controller:
[HttpPost]
public ActionResult GetSchedules(int generationId, IEnumerable<StateViewModel> states)
{
return View("Index");
I can't pass values to my controller. I've managed to pass only statesData
object without jQuery and using type="submit"
in my form. When I tried to pass only statesData
with jQuery and type="button"
I got "Invalid JSON primitive" error in FireBug.
When I tried to pass integer + statesData
object, IE 9 is crashing and Firefox hangs.
I've tried various solutions but without success.
Try like this:
function ShowReportSchedules() {
var selectedGenerationId = $('#SelectedGenerationId').val();
$.ajax({
type: 'POST',
url: '@Url.Action("getschedules", "home")?generationId=' + selectedGenerationId,
data: { states: $('#checkboxFrm').serialize() },
success: function(result) {
// Do something with the results
}
});
};
var a = $("#a").serialize();
var b = $("#b").serialize();
var c = $("#c").serialize();
$.ajax({
url: '@Url.Content("~/Controller/Method1")',
type: 'POST',
data: a+b+c,
success: function (success) {
// do something
}
});
// in Controller
[HttpPost]
public ActionResult Method1(abc a, bcd b, xyz c)
{
}
// where abc, bcd xyz are class
精彩评论