[英]Not able to pass the values from MVC(Razor) view to JsonResult method in Controller
我的MVC(剃刀)視圖中有兩個下拉列表:國家和州。 我能夠彼此獨立地填充兩個下拉列表。現在,我想基於“國家/地區”下拉列表的更改事件來填充第二個下拉列表(州)。
為此,我在Controller中使用了JsonResult方法,並且為此方法,我從視圖中傳遞了Country的Change事件上的countryID,以填充第二個下拉狀態。
問題陳述: JsonResult方法從我的視圖中被觸發,但是CountryId值未從視圖傳遞到控制器以按順序填充狀態。
我在這里做錯了什么?
視圖:
Javascript:
<script type="text/JavaScript">
function CountryChange() {
var url = '@Url.Content("~/MasterConfigGeneral/GetState")';
var ddlsource = "#CountryID";
var ddltarget = "#StateID";
if ($(ddlsource).val() != "") {
$.ajaxSetup({ cache: false });
$.getJSON(url, { countryID: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$("#StateID").append("<option value=''>Select State</option>");
$.each(data, function (index, optionData) {
$("#StateID").append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
else {
$("#StateID").empty();
$("#StateID").append("<option value=''>Select State</option>");
}
}
</script>
下拉菜單在我看來:
<div class="cssclass">
@Html.DropDownListFor(model => model.companyModel.CountryID, new SelectList(Model.ddlCountryStateCity.ddlCountry, "Value", "Text"), "Select Country", new { onchange="CountryChange()" })
@Html.ValidationMessageFor(model => model.companyModel.CountryID)
</div>
<div class="cssclass">
@Html.LabelFor(model => model.companyModel.StateID)
</div>
<div class="editor-field">
@Html.DropDownList("stateid",Model.ddlCountryStateCity.ddlState,"Select State")
@Html.ValidationMessageFor(model => model.companyModel.StateID)
</div>
控制器:
國家下拉列表:
#region Country
public DropdownListCountryStateCity FillDropDownListCountry()
{
objDropDownCountryStateCity.ddlCountry = (from s in dbEntity.Countries
select new SelectListItem()
{
Text = s.Name,
Value = s.CountryID
}).ToList<SelectListItem>();
return objDropDownCountryStateCity;
}
#endregion
狀態下拉列表:
#region State
public JsonResult GetState(string countryID)
{
JsonResult jsResult = new JsonResult();
objDropDownCountryStateCity.ddlState = (from csc in dbEntity.CountryStateCities
join c in dbEntity.Countries on csc.CountryID equals c.CountryID
join s in dbEntity.States on csc.StateID equals s.StateID
where csc.CountryID == countryID
select new SelectListItem()
{
Text = s.Name,
Value = s.StateID
}).ToList<SelectListItem>();
jsResult.Data = objDropDownCountryStateCity.ddlState;
jsResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsResult;
}
#endregion
您的問題在於DropDownListFor助手如何生成元素。
在您的代碼中,它將生成類似以下的名稱和ID:
<select id="companyModel_CountryID" name="companyModel.CountryID">
...
</select>
在您的JavaScript中,ddlSouce是“ #CountryID”。 由於沒有具有該ID的元素,因此jQuery將null作為數據傳遞給$ .getJSON。 這就是為什么控制器方法什么也沒收到的原因。
您有兩種選擇:
new { onchange="CountryChange()" }
至
new { id = "CountryID", onchange="CountryChange()" }
恕我直言,最后的選擇是最好的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.