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

时间:2017-01-09 14:53:58

标签: asp.net-mvc data-binding model

我正在做一个MVC APP,我有一个具有实体的模型视图和一个IList,它在Controller中填充以填充DropdownList。

这是我的ViewModel



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

User is a class

控制器看起来像这样。

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

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

视图是从

导入的普通视图
@model TableAvivaVoz.Models.UserViewModel

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

我发现的问题是在提交视图时。在Create Method上,看起来像这样。

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

如果我的Create方法返回UserViewModel实例,则所有属性都为空。

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

但是,如果错误发生,我不知道如何调用返回AvailableCountries实例的UserViewModel方法......

&#13;
&#13;
 [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);
            }
&#13;
&#13;
&#13;

我的问题是,当我有实例或用户而不是UserViewModel时,如何调用AvailableCountries方法?

感谢

这是我的观点...

&#13;
&#13;
@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")
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以从“创建”操作返回相同的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);
    }
}

答案 1 :(得分:1)

我认为你应该改变它,所以你把它留给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);
        }