2014-11-05 103 views
-1

我是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初學者。任何幫助或解釋都會有幫助。

Breakpoint at userdata object

Breakpoint at ModelState. Here in the role,country,and for bu i am getting the null value. but in the userdata object the value is showing.

+0

什麼是驗證信息? – Michael 2014-11-05 12:09:54

+0

我的意思是說我的模型在執行(Modelstate.isvalid)時會失效。即使我正在使用create action方法獲取所有值。 – user3132179 2014-11-05 12:15:00

+0

在您的創建方法中放置一個斷點,一旦命中,展開ModelState對象並檢查字典中的所有對象,以瞭解哪些屬性的驗證失敗。 – SBirthare 2014-11-05 12:15:53

回答

1

你的調令回你的數據模型(包括作爲您的視圖模型的屬性)。數據模型的[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(或者可以將這些默認值放入構造函數中)並保存到數據庫。

+0

感謝細節..一個混亂。爲什麼你在第一個解決方案中有兩個@Html? – user3132179 2014-11-06 07:58:57

+0

只是一個愚蠢的錯字! – 2014-11-06 08:04:39