网上看到的例子,当将model当成一个属性时,验证方法传过来的参数就为空?源码如下
model类:
public class User { [Required(ErrorMessage="姓名不能为空")] [Remote("IsUnique_Available","Home")] public string Name { get; set; } } 封装后的Users类 public class EditUserVM { /// <summary> /// User VM /// </summary> public User Users { get; set; } }
view页面:
@model MvcRemoteValidation.ViewModels.UserViewModels.EditUserVM @{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Create</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>User</legend> <div class="editor-label"> @Html.LabelFor(model => model.Users.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Users.Name) @Html.ValidationMessageFor(model => model.Users.Name) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>
Controller中的代码:
public JsonResult IsUnique_Available(string Name)//User封装成属性后无法取到值? { List<User> users = UserService.GetUsers(); users = users.Where(u => u.Name == Name).ToList(); if (users.Count == 0) return Json(true, JsonRequestBehavior.AllowGet); string suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} 已经存在。", Name); return Json(suggestedUID, JsonRequestBehavior.AllowGet); }
这时,IsUnique_Available方法中的参数name,传过来的都为null ? 但如果在view页面,直接用User,参数就可取到值,请问各位,是什么原因?谢谢!
查看一下生成的html,你就会发现提交的参数存在问题。当用EditUserVM时,提交的是Users.Name,构建Model时,会找叫Users的参数,而不是叫Name的参数。IsUnique_Available方法的签名改成(User Users=null, string Name=null)也许能解决你的问题。
@无名草: 还有一点值得注意:IsUnique_Available(User _User)中定义的参数,要与 EditUserVM 中属性名称一样:即应该为:IsUnique_Available(User Users) 。
最佳方案:
public JsonResult IsUnique_Available(EditUserVM vm) { List<User> users = UserService.GetUsers(); users = users.Where(u => u.Name == vm.Users.Name).ToList(); if (users.Count == 0) return Json(true, JsonRequestBehavior.AllowGet); string suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} 已经存在。", vm.Users.Name); return Json(suggestedUID, JsonRequestBehavior.AllowGet); }