模型视图模型失效viewmodel控制器
我是ASP.NET MVC 5的新手。我试图制作一个用户管理软件。但在用户注册(创建)控制器中,我的模型已失效。不知道为什么。我可能在我的模型绑定中发生错误。这是附加的代码。任何帮助表示赞赏。模型视图模型失效viewmodel控制器
型号文件
public class UserData
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int userid { get; set; }
[Required(ErrorMessage = "Domain ID")]
[Display(Name = "Domain ID")]
public string domainid { get; set; }
[Required(ErrorMessage = "Choose Role")]
[Display(Name = "Role")]
public string role { get; set; }
[Required(ErrorMessage = "Choose Country")]
[Display(Name = "Country")]
public string country { get; set; }
[Required(ErrorMessage = "Choose BU")]
[Display(Name = "BU")]
public string bu { get; set; }
[Required]
[RegularExpression(@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$", ErrorMessage = "Please Provide Valid Email-ID")]
[Display(Name = "Email"),DataType(DataType.EmailAddress)]
public string email { get; set; }
[HiddenInput(DisplayValue=true)]
public DateTime date_from { get; set; }
[HiddenInput(DisplayValue = true)]
public DateTime date_to { get; set; }
[HiddenInput(DisplayValue=true)]
public bool active { get; set; }
}
视图模型文件
public class UserRegistrationViewModel
{
public UserData userdata { get; set; }
public string SelectedRole { get; set; }
public IEnumerable<SelectListItem> RoleList { get; set; }
public string SelectedCountry { get; set; }
public IEnumerable<SelectListItem> CountryList { get; set; }
public string SelectedBU { get; set; }
public IEnumerable<SelectListItem> BUList { get; set; }
}
控制器的文件
public class UserDatasController : Controller
{
private ApplicationDataContext db = new ApplicationDataContext();
// GET: UserDatas
public ActionResult Index()
{
return View(db.UsersData.ToList());
}
public ActionResult Create()
{
var model = new UserRegistrationViewModel();
model.CountryList = from p in XDocument.Load("C:/Users/inkosah/Documents/Visual Studio 2013/Projects/Policy Assessment/Policy Assessment/country_list.xml").Descendants("Name")
//var a=Path.GetFullPath("Policy Asse")
let value = (string)p.Element("Text")
select new SelectListItem
{
Selected = (value == model.SelectedCountry),
Text = (string)p.Element("Text"),
Value = value
};
model.BUList = from q in XDocument.Load("C:/Users/inkosah/Documents/Visual Studio 2013/Projects/Policy Assessment/Policy Assessment/bu_list.xml").Descendants("BU")
let value2 = (string)q.Element("BU_Name")
select new SelectListItem
{
Selected = (value2 == model.SelectedBU),
Text = (string)q.Element("BU_Name"),
Value = value2
};
model.RoleList = from n in XDocument.Load("C:/Users/inkosah/Documents/Visual Studio 2013/Projects/Policy Assessment/Policy Assessment/UserRoleList.xml").Descendants("Role")
let value1 = (string)n.Element("Role_Name")
select new SelectListItem
{
Selected = (value1 == model.SelectedRole),
Text = (string)n.Element("Role_Name"),
Value = value1
};
return View(model);
}
// POST: UserDatas/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "SelectedRole,SelectedCountry,SelectedBU")]UserRegistrationViewModel RegisterData,[Bind(Include="domainid,email")] UserData userdata)
{
userdata.date_from = DateTime.Now;
userdata.date_to = DateTime.MaxValue;
userdata.active = false;
userdata.role = RegisterData.SelectedRole;
userdata.bu = RegisterData.SelectedBU;
userdata.country = RegisterData.SelectedCountry;
if (ModelState.IsValid)
{
db.UsersData.Add(userdata);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userdata);
}
create.cshtml
@model Policy_Assessment.ViewModels.UserRegistrationViewModel
@{
ViewBag.Title = "User Registration Page";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User Input</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.userdata.domainid, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.userdata.domainid)
@Html.ValidationMessageFor(model => model.userdata.domainid)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.userdata.role, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@*@Html.EditorFor(model => model.role)*@
@Html.DropDownListFor(model => model.SelectedRole, Model.RoleList, "-----Role-----")
@Html.ValidationMessageFor(model=>model.SelectedRole)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.userdata.country, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@*@Html.EditorFor(model => model.country)*@
@Html.DropDownListFor(model => model.SelectedCountry,Model.CountryList,"----Country-----")
@Html.ValidationMessageFor(model => model.userdata.country)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.userdata.bu, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model=>model.SelectedBU,Model.BUList,"--Select BU----")
@Html.ValidationMessageFor(model => model.userdata.bu)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.userdata.email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.userdata.email)
@Html.ValidationMessageFor(model => model.userdata.email)
</div>
</div>
@*<div class="form-group">
@Html.HiddenFor(model => model.userdata.date_from, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(model => model.userdata.date_from)
@Html.ValidationMessageFor(model => model.userdata.date_from)
</div>
</div>
<div class="form-group">
@Html.HiddenFor(model => model.userdata.date_to, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(model => model.userdata.date_to)
@Html.ValidationMessageFor(model => model.userdata.date_to)
</div>
</div>
<div class="form-group">
@Html.HiddenFor(model => model.userdata.active, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(model => model.userdata.active)
@Html.ValidationMessageFor(model => model.userdata.active)
</div>
</div>*@
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Register" class="btn btn-default" />
</div>
</div>
</div>
}
@*<div>
@Html.ActionLink("Back to List", "Index")
</div>*@
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
上下文文件
public class ApplicationDataContext : DbContext
{
public ApplicationDataContext()
: base("DefaultConnection")
{ }
public System.Data.Entity.DbSet<Policy_Assessment.ViewModels.UserRegistrationViewModel> UserRegistrationData { get; set; }
public System.Data.Entity.DbSet<Policy_Assessment.Models.UserData> UsersData { get; set; }
}
请注意我在MVC ASP.Net初学者。任何帮助或解释都会有帮助。
你的调令回你的数据模型(包括作为您的视图模型的属性)。数据模型的[Required]
属性为role
,但您正在为此属性创建控件,因此没有任何约束,这意味着它的null
因此无效。两种方法来解决这个问题。
A.从视图模型中取出财产string SelectedRole
,并直接绑定到中包含的内容视图模型现在
@Html.DropDownListFor(m => m.userdata.role, Model.RoleList, ...)
的数据模型,userdata.role
将包含选择的选项值,将是有效的(注意,您将需要为其他2个属性做这个)。
B.从视图模型中取出财产3210和视图模型包括来自UserData
属性正在编辑
public class UserRegistrationViewModel
{
[Required(ErrorMessage = "Domain ID")]
[Display(Name = "Domain ID")]
public string domainid { get; set; }
[Required(ErrorMessage = "Choose Role")]
[Display(Name = "Role")]
public string role { get; set; }
[Required(ErrorMessage = "Choose Country")]
[Display(Name = "Country")]
public string country { get; set; }
[Required(ErrorMessage = "Choose BU")]
[Display(Name = "BU")]
public string bu { get; set; }
[Required]
[Display(Name = "Email"),DataType(DataType.EmailAddress)]
[EmailAddress]
public string email { get; set; }
public SelectList RoleList { get; set; }
public SelectList CountryList { get; set; }
public SelectList BUList { get; set; }
}
注意我已经排除属性,你似乎没有被编辑,使用[EmailAddress]
,而不是你的正则表达式(看不出什么的正则表达式就是这么做的EmailAddress
属性尚未执行),并使用SelectList
而不是IEnumerable<SelectListItem>
这意味着你可以把它简化为
public ActionResult Create()
{
var model = new UserRegistrationViewModel();
var roles = from n in XDocument.Load(....
model.RoleList = new SelectList(roles, "value", "value");
....
return View(model);
}
然后在POST方法中,将视图模型中的属性映射到数据模型的新实例,并根据需要设置其他属性,如date_from
(或者可以将这些默认值放入构造函数中)并保存到数据库。
感谢细节..一个混乱。为什么你在第一个解决方案中有两个@Html? – user3132179 2014-11-06 07:58:57
只是一个愚蠢的错字! – 2014-11-06 08:04:39
什么是验证信息? – Michael 2014-11-05 12:09:54
我的意思是说我的模型在执行(Modelstate.isvalid)时会失效。即使我正在使用create action方法获取所有值。 – user3132179 2014-11-05 12:15:00
在您的创建方法中放置一个断点,一旦命中,展开ModelState对象并检查字典中的所有对象,以了解哪些属性的验证失败。 – SBirthare 2014-11-05 12:15:53