将数据从视图传递到方法在控制器中创建

时间:2017-07-29 00:44:59

标签: asp.net-mvc razor

我在控制器中将数据传递给metod创建时遇到以下问题。 首先,我显示方法创建(GET)的视图

public ActionResult Create(string id)
        {
            RolesUser RolesUser = new RolesUser(id,repository.GetUserById(id).Roles, repository.GetRoles().ToList());          
            return View(RolesUser);
        }

我使用以下ViewModel

public class RolesUser
    {
        public RolesUser()
        {

        }

        public RolesUser(string id,ICollection<IdentityUserRole> userRoles,List<IdentityRole> Roles)
        {
            userId = id;
            this.Roles = GetNewRolesForUser(userRoles.ToList(), Roles.ToDictionary(x => x.Id, x => x.Name)).ConvertAll(
                role =>
                {
                    return new SelectListItem()
                    {
                        Text = role.ToString(),
                        Value = role.ToString(),
                        Selected = false
                    };
                });
        }

        public IEnumerable<SelectListItem> Roles { get; set; }

        public string userId { get; set; }

        private List<string> GetNewRolesForUser(List<IdentityUserRole> UserRoles,Dictionary<string,string> Roles)
        {
            List<string> AvaiableRoles = new List<string>();
            List<string> IdUserRoles = new List<string>();
            UserRoles.ForEach(item => IdUserRoles.Add(item.RoleId));

            foreach(KeyValuePair<string,string> Role in Roles)
            {
                if (!IdUserRoles.Contains(Role.Key))
                {
                    AvaiableRoles.Add(Role.Value);
                }
            }
            return AvaiableRoles;
        }

    }

它在Create.cshtml中向我显示我的视图的基本信息,当我执行提交时,它显示我跟随错误 对象引用未设置为对象的实例。

metod create(POST)看起来像这样

[HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles ="Admin")]
        public ActionResult Create([Bind(Include ="userId")] RolesUser user)
        {
            if (ModelState.IsValid)
            {
                try
                {

                    repository.AssignToRole(user.userId, "Klient");
                    repository.SaveChanges();
                }
                catch
                {
                    ViewBag.exception = true;
                    return View();
                }    
            }
            ViewBag.exception = false;
            return RedirectToAction("Index");
        }

Create.cshtml代码

@model Repository.ViewModels.RolesUser

@{
    ViewBag.Title = "Create";
}

<h2>Dodaj poziom dostępu</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>@Model.userId</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.userId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DisplayFor(model => model.userId, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>

        <div class="form-group">
        @Html.Label("Poziomy dostępu", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.userId, Model.Roles)
        </div>
        </div>



        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Dodaj" class="btn btn-default" />
            </div>
        </div>
    </div>
}

看起来viewmodel没有传递给方法,所以我有null异常。但我不明白为什么,如果GET metod呈现正确的视图。

1 个答案:

答案 0 :(得分:0)

NullReferenceException很可能在repository.AssignToRole()方法中被触发,因为user.userId为空。您应该在表单内的某处为userId添加隐藏输入,以便将userId值发布到Create操作上的参数对象。如果您在@Html.AntiForgeryToken()表单开头之后添加它

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.userId)

    ...