模型视图viewmodel控制器中的模型失效

时间:2014-11-05 12:00:02

标签: c# asp.net-mvc asp.net-mvc-5

我是ASP.NET MVC 5的新手。我正在尝试制作用户管理软件。但在用户注册(创建)控制器中,我的模型正在失效。不知道为什么。我的模型Binding可能有错误。这是附加的代码。任何帮助表示赞赏。

模型文件

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; }

       }

ViewModel文件

 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.

1 个答案:

答案 0 :(得分:1)

您回发数据模型(包含在视图模型的属性中)。数据模型具有属性[Required]的{​​{1}}属性,但您正在为此属性创建控件,因此不会绑定任何内容,这意味着它的role因此无效。解决这个问题的两种方法。

一个。从视图模型中删除属性null并直接绑定到视图模型中包含的数据模型

string SelectedRole

现在,@Html.DropDownListFor(m => m.userdata.role, Model.RoleList, ...) 将包含所选的选项值并且有效(请注意,您还需要为其他2个属性执行此操作)。

B中。从视图模型中删除属性userdata.role,并在视图模型中包含您正在编辑的UserData userdata的属性

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>

然后在POST方法中,将视图模型中的属性映射到数据模型的新实例,如果需要,设置其他属性,如public ActionResult Create() { var model = new UserRegistrationViewModel(); var roles = from n in XDocument.Load(.... model.RoleList = new SelectList(roles, "value", "value"); .... return View(model); } (或者,您可以将这些默认值放在构造函数中) )并保存到数据库。