当我使用此代码时,我收到内部服务器错误:
<script>
function LoadRegion() {
var countryId = document.getElementById("country").value;
$.ajax({
type: 'POST',
url: "../Account/Register",
data: $('#form').serialize(),
dataType: 'json'
});
}
</script>
我的问题是:如何在特定字段的控制器中传递此值?
控制器:
[HttpPost]
public ActionResult Register(IndexPageModel model)
{
model.Register.Country = new SelectList(manager.GetCountries(), "Id", "Name");
//I need to put here SelectCountryId->model.Register.Region = new SelectList(manager.GetRegions(model.Register.SelectCountryId), "Id", "Name");
return View(model);
}
查看:
@Html.DropDownListFor(m => m.Register.SelectCountryId,
Model.Register.Country,
"Select country",
new { id = "country",
@class = "form-control",
@onchange ="LoadRegion();"
}
)
答案 0 :(得分:1)
在谈到这个问题之后,我们提出了以下解决方案:
您需要创建一个仅返回要返回的值的操作方法。在这个例子中,它是一个区域列表,以便您可以填充选择列表。
public JsonResult GetCities(int countryId)
{
IUserManager manager = UserFactory.GetUserManager(WebConfiguration.TerminalId);
var model = manager.GetRegions(countryId);
return Json(model);
}
在JavaScript中,您需要向此操作方法发出请求,并添加要添加到选择列表的选项:
function LoadRegion() {
var cities = $('#CitiesSelectBox');
var url = "/Account/GetCities";
$.getJSON(url, { countryId: $('#CountryID').val() }, function (response) {
cities.empty().append($('<option></option>').val('').text('Please select'));
for (var i = 0; i < response.length; i++) {
cities.append($('<option></option>').val(response[i].Id).text(response[i].Name));
}
});
}
您获得的服务器错误是因为您需要允许对JSON数据的get请求。默认情况下不启用此选项:
// Enable GET requests on JSON response
return Json(model, JsonRequestBehavior.AllowGet)