C#MVC下拉列表未更新模型

时间:2016-09-26 11:01:38

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

当我从下拉列表控件中选择一个新值时,我对于为什么我的模型没有更新有疑问?

这是我的模特

public class UserViewModel
{
    public Users users { get; set; }                
    public IEnumerable<SelectListItem> UserRoles { get; set; }                
}

控制器

//GET
public ActionResult Edit(int id)
{
        var vm = new UserViewModel();
        vm.users = repository.GetById(id);

        vm.UserRoles = db.UserRoles.Select(
                            x => new SelectListItem
                            {
                                Selected = true,
                                Text = x.UserRoleName,
                                Value = x.UserRoleID.ToString()
                            }
            );

        if (vm == null)
        {
            return HttpNotFound();
        }
        return View(vm);
   }


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserViewModel model)
{
        if(ModelState.IsValid)
        {
            db.Entry(model).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View();       
 }

最后我的观点

<div class="form-group">
<label class="control-label col-md-2">User Role</label>
<div class="col-md-10">
       @Html.HiddenFor(model => model.users.UserRoleID)
       @Html.DropDownListFor(model => model.UserRoles, (IList<SelectListItem>)ViewBag.UserRoles, "-- Select One --", new { @class = "form-control" })                
     </div>
 </div>

我已经逐步完成了代码,并且在集合中可以看到集合中的UserRoles,但我不确定我是否正确传递了值?

更新

我更新了POST方法来更新模型

public ActionResult Edit(int id, UserViewModel model)
{
        var user = repository.GetById(id);
        if (ModelState.IsValid)
        {
            if (user != null)
            {
                user.Username = model.users.Username;
                user.Forename = model.users.Forename;
                user.Lastname = model.users.Lastname;
                user.Email = model.users.Email;
                user.Status = model.users.Status;
                user.UserRoleID = Convert.ToInt32(model.UserRoles);

                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }                
        }
        return View();         
    }

但是在提交时它会在下拉列表中给我Null reference例外,如下所示?现在明白为什么?

Null reference exception

3 个答案:

答案 0 :(得分:1)

@app.route('/media/<path:filename>')
def media(filename):
    return send_from_directory(app.config['MEDIA_FOLDER'], filename.encode(app.config['ENCODING']))

您的数据存在于(IList<SelectListItem>)ViewBag.UserRoles 列表中但不在vm.UserRoles但是您使用Viewbag附加列表

ViewBag.UserRoles

将列表分配给视图模型,然后您将可以访问页面中的列表

答案 1 :(得分:0)

终于解决了这个问题。在我的ViewModel中创建了一个新属性,该属性将存储当回发到Controller

时的选定值
public class UserViewModel
{
    public Users users { get; set; }                
    public IEnumerable<SelectListItem> UserRoles { get; set; }                    
    public string selectedRole { get; set; }
}

对我的视图进行了更改以包含新属性

@Html.DropDownListFor(model => model.selectedRole, Model.UserRoles, "-- Select One --", new { @class = "form-control" })

并在帖子上传递选定的值

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, UserViewModel model)
{
    var user = repository.GetById(id);
    if (ModelState.IsValid)
    {
       if (user != null)
       {
           user.Username = model.users.Username;
           user.Forename = model.users.Forename;
           user.Lastname = model.users.Lastname;
           user.Email = model.users.Email;
           user.Status = model.users.Status;
           user.UserRoleID = Convert.ToInt32(model.selectedRole);           

           db.Entry(user).State = EntityState.Modified;
           db.SaveChanges();
           return RedirectToAction("Index");
       }
       else
       {
           return View();
       }                
        return View();         
    }

答案 2 :(得分:0)

我认为视图中的代码错误:

<div class="col-md-10"> @Html.HiddenFor(model => model.users.UserRoleID) @Html.DropDownListFor(model => model.UserRoles (IList<SelectListItem>)ViewBag.UserRoles, "-- Select One --", new { @class = "form-control" }) </div>

下一个代码应该起作用:

<div class="col-md-10"> @Html.DropDownListFor(model => model.users.UserRolesID, new SelectList(Model.UserRoles, "Id", "Name"), new { @class = "form-control" }) </div>

在model.users.UserRolesID和包含用户角色的列表之间有直接绑定(我假设UserRoles是通过id,description完成的)