![](/img/trans.png)
[英]Passing Json data to MVC controller - Action Method's JObject Parameter
[英]MVC ListBox not passing data to Action
當我使用 FireBug 時,我看到 selectedPrdLctn 的選定值設置正確,但是當我將它通過 JSON 傳遞給我的操作時,它是 null
$.getJSON('@Url.Action("GetCS")', { cntrParam: selectedPrdLctn }, function (getCS) {
我的行動
public ActionResult GetCS(String[] cntrParam)
如果我使用 dropDownList,代碼就可以工作。 知道為什么我不通過選擇嗎?
我懷疑問題出在您沒有設置traditional
參數並且 jQuery 沒有以默認 model 活頁夾能夠理解的格式發送集合。 如果您使用的是 jQuery 1.4 或更高版本,則必須設置此參數。
例如:
Model:
public class MyViewModel
{
public string[] SelectedValues { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Items = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
new SelectListItem { Value = "4", Text = "item 4" },
}
};
return View(model);
}
public ActionResult GetCS(string[] values)
{
return Json(new
{
message = string.Format("{0} item(s) selected", values.Length)
}, JsonRequestBehavior.AllowGet);
}
}
看法:
@model MyViewModel
@Html.ListBoxFor(
x => x.SelectedValues,
Model.Items,
new {
id = "mylist",
}
)
@Html.ActionLink("Send AJAX", "getcs", null, new { id = "mylink" })
腳本:
$(function () {
$('#mylink').click(function () {
var selectedValues = $('#mylist').val();
$.getJSON(this.href, $.param({ values: selectedValues }, true), function (result) {
alert(result.message);
});
return false;
});
});
請注意我是如何使用$.param
.param function 並將其作為代表傳統參數的第二個參數傳遞給 true 的。 嘗試使用true
和false
調用它,您將看到 FireBug 中的差異,並且您將理解為什么如果不設置此參數它就不起作用。
您還可以為所有 AJAX 請求全局設置此參數:
$.ajaxSetup({
traditional: true
});
然后以下將起作用:
$.getJSON(this.href, { values: selectedValues }, function (result) {
alert(result.message);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.