当我使用此代码时,我收到内部服务器错误:
<script>
function LoadRegion() {
var countryId = document.getElementById("country").value;
$.ajax({
type: 'POST',
url: "../Account/Register",
data: $('#form').serialize(),
dataType: 'json'
});
}
</script>
我的问题是:我如何在特定字段的 Controller 中传递这个值?
Controller :
[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();"
}
)
最佳答案
经过讨论这个问题,我们得出了以下解决方案:
您需要创建一个仅返回您想要返回的值的操作方法。在本例中,它是一个区域列表,以便您可以填充选择列表。
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 数据的获取请求。默认情况下未启用此功能:
// Enable GET requests on JSON response
return Json(model, JsonRequestBehavior.AllowGet)
关于javascript - 内部服务器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30477641/