【发布时间】:2016-10-26 02:02:23
【问题描述】:
大家好,
我正在尝试使用 Razor mvc3 编写一个简单的注册表单,使用 jquery 自动完成功能从数据库中填充城市、州信息。 razor 视图使用表单验证,jquery 填充文本框信息。但是,当将数据从所述文本框传递到控制器时,值始终为空。
视图中的文本框:
<input data-autocomplete="@Url.Action("AutoCompleteCity", "Search")" class="form-control" placeholder="Enter City" name="city" id="city" />
我也尝试过这种替代方法,但无济于事:
@Html.TextBoxFor(u => u.city, new { @class="form-control", @placeholder="Enter city"})
控制器(registration.city 始终为空):
if (registration.city == null) ModelState.AddModelError("", "Must select City.");
Jquery 自动完成:
$("#city").
autocomplete({
source: function (request, response) {
$.ajax({
url: serviceURL,
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
$("#targetDiv").append($("<ul id='targetUL' class='list-group'></ul>"));
//Removing previously added li elements to the list.
$("#targetUL").find("li").empty();
$.each(data, function (i, value) {
//On click of li element we are calling a method.
$("#targetUL").append($("<li class='list-group-item' onclick='javascript:addText(this)'>" + value.city + ", " + value.state + "</li>"));
});
}
})
},
任何帮助将不胜感激。我对 Razor 有点陌生,所以我可能一定遗漏了一些东西。谢谢!!
编辑 - 控制器代码:
[HttpPost]
public ActionResult register(Models.UserForm registration)
{
if (registration.email != null && registration.email.Length > Constants.MAX_MAIL_SIZE) ModelState.AddModelError("longUsername", "Username is too long");
if (registration.email != null && !registration.email.Contains('@')) ModelState.AddModelError("wrongEmail", "Email is not valid.");
if (registration.email == null || registration.email.Trim().Length == 0) ModelState.AddModelError("", "Name cannot be blank.");
if (registration.password != null && registration.password.Length > Constants.MAX_PASS_SIZE) ModelState.AddModelError("", "Password is too long.");
if (registration.password == null || registracion.contrasenia.Trim().Length == 0) ModelState.AddModelError("", "Password cannot be blank.");
if (registration.name != null && registration.name.Length > Constantes.MAX_NOMBRE_SIZE) ModelState.AddModelError("", "Name is too long.");
if (registration.name == null || registration.name.Trim().Length == 0) ModelState.AddModelError("", "Name cannot be blank.");
if (registration.city == null) ModelState.AddModelError("", "Must Select City.");
if (!db.validateExistingUser(registration.email)) ModelState.AddModelError("", "User already exists.");
if (!ModelState.IsValid)
{
return View();
}
else
{
Usuario u = db.registerUser(registracion);
Session["User"] = u;
return View("Index");
}
}
【问题讨论】:
标签: jquery asp.net-mvc razor autocomplete