繁体   English   中英

调用Create或Update方法时,来自不同模型的mvc视图模型绑定

[英]mvc view model binding from different Model when call Create or Update Method

我正在做一个MVC APP,我有一个具有en Entity的ModelView和一个填充在Controller中以填充DropdownList的IList。

这是我的ViewModel

  public class UserViewModel { public Users user { get; set; } public IList<SelectListItem> AvailableCountries { get; set; } } 

User is a class

控制器看起来像这样。

  public ActionResult Create() { var countries = GetCountries(); var model = new UserViewModel { AvailableCountries = countries }; return View(model); } 

GetCountries是一个返回国家列表的函数。

该视图是从中导入的普通视图

@model TableAvivaVoz.Models.UserViewModel

我认为其余的View不重要...每个元素都从model.user.继承model.user.

我发现的问题是在提交视图时。 在创建方法上,看起来像这样。

public async Task<ActionResult> Create([Bind(Include = "Country_id,Name,LastName,Sex,CodArea,PhoneNumber,Email,Password,ConfirmPassword")] Users user)

如果我的Create方法重新调整了UserViewModel实例,则所有属性均为null。

它获得了User类的所有属性,这是我的UserViewModel类的一部分。

但是,如果发生错误,我不怎么调用返回UserViewModel实例的AvailableCountries方法。

  [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "Country_id,Name,LastName,Sex,CodArea,PhoneNumber,Email,Password,ConfirmPassword")] Users user) { try { if (ModelState.IsValid) { _db.Users.Add(user); _db.SaveChanges(); return RedirectToAction("Create"); } UserViewModel.AvailableCountries = GetCountries();//error return View(user); } 

我的问题是,当我有一个实例或User或UserViewModel时,如何调用AvailableCountries方法?

谢谢

这是我的观点...

 @model TableAvivaVoz.Models.UserViewModel @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Users</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.user.Country_id, "Country", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.user.Country_id, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.user.Name, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.user.Name, new { htmlAttributes = new { @class = "form-control", placeholder = "Nombre" } }) @Html.ValidationMessageFor(model => model.user.Name, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.user.LastName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.user.LastName, new { htmlAttributes = new { @class = "form-control", placeholder = "Apellido" } }) @Html.ValidationMessageFor(model => model.user.LastName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.user.Sex, "Género", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.Label("Hombre") @Html.RadioButtonFor(model => model.user.Sex, "1", new { htmlAttributes = new { @class = "form-control" } }) @Html.Label("Mujer") @Html.RadioButtonFor(model => model.user.Sex, "0", new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.user.Sex, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.user.CodArea, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.user.CodArea, new { htmlAttributes = new { @class = "form-control", placeholder = "Cód Area" } }) @Html.ValidationMessageFor(model => model.user.CodArea, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.user.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.user.PhoneNumber, new { htmlAttributes = new { @class = "form-control", placeholder = "Número Telefono" } }) @Html.ValidationMessageFor(model => model.user.PhoneNumber, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.user.Email, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.user.Email, new { htmlAttributes = new { @class = "form-control", placeholder = "Email" } }) @Html.ValidationMessageFor(model => model.user.Email, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.user.Password, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.PasswordFor(model => model.user.Password, new { @class = "form-control", placeholder = "Contraseña" }) @Html.ValidationMessageFor(model => model.user.Password, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.user.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.PasswordFor(model => model.user.ConfirmPassword, new { @class = "form-control", placeholder = "Repetir Contraseña" }) @Html.ValidationMessageFor(model => model.user.ConfirmPassword, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div style="position:relative;"> <label>Image</label> <div>Upload new image: <input type="file" name="Image" /></div> </div> @if (Model.user == null || Model.user.Picture == null) { <div class="form-control-static">No Image</div> } @*else { <img class="img-thumbnail" width="150" height="150" src="@Url.Action("GetImage", "Product",new { Model.ProductID })" /> }*@ </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } 

您可以从Create操作返回相同的UserViewModel

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Country_id,Name,LastName,Sex,CodArea,PhoneNumber,Email,Password,ConfirmPassword")] Users user)
{
    try
    {
        if (ModelState.IsValid)
        {
            _db.Users.Add(user);
            _db.SaveChanges();
            return RedirectToAction("Create");
        }

        var model = new UserViewModel 
        { 
            user = user,
            AvailableCountries = GetCountries(),
        };

        return View(model);
    }
}

我认为您应该更改它,以便将其保留为自动绑定MVC,这更加干净

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(UserViewModel model)
        {
                if (ModelState.IsValid)
                {
                    var user = new User();
                    user.FirstName = model.User.FirstName;
                    //........ rest of the properties here
                    _db.Users.Add(user);
                    _db.SaveChanges();
                    return RedirectToAction("Create");
                }

                model.AvailableCountries = GetCountries();//error
                return View(model);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM