MVC Razor DropDownListFor未在模型中设置的值

时间:2017-03-30 07:50:44

标签: c# asp.net-mvc razor

我正在尝试制作一个可以将模型发布到我的控制器的剃刀视图。

我添加了一个下拉列表,但是当我发布到我的控制器时,platform总是null

我做错了什么?

这是我的观点

@using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @class = "form-horizontal", @id = "form" }))
{
    @{
        var platformList = new List<SelectListItem>() {
            new SelectListItem(){ Value="I", Text="iOS"},
            new SelectListItem(){ Value="A", Text="Android"},
        };
    }
    <div class="form-group">
        @Html.LabelFor(model => model.platform, "Plattform", new { @for = "inputPlatform", @class = "col-lg-3 control-label" })
        <div class="col-lg-9">
            @Html.DropDownListFor(model => model.platform, platformList, new { @class = "form-control", @id = "inputPlatform" })
        </div>
    </div>
}

这是我的模特

public class RegistrationModel
{
    public String platform { get; set; }
}

我的控制器

[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegistrationModel RegistrationModelViewModel)
{

}

1 个答案:

答案 0 :(得分:1)

我无法让你的观点发挥作用。下拉声明似乎存在格式问题。它有一个额外的逗号,并且错过了结束}。我一直得到一个解析错误,这很奇怪,因为你说你可以让帖子工作。

无论如何,我在下面创建了一个有效的例子,所以我希望它有用。

模型

 public class RegistrationModel
 {
        public string platform { get; set; }
 }

查看

@model TestMVC.Models.RegistrationModel

@using (Html.BeginForm("Register", "Register", FormMethod.Post, new { @class = "form-horizontal", @id = "form" }))
{
    var platformList = new List<SelectListItem>() {new SelectListItem(){ Value="I", Text="iOS"}, new SelectListItem(){ Value="A", Text="Android"}};

    <div class="form-group">
        @Html.LabelFor(model => model.platform, "Plattform", new {@for = "inputPlatform", @class = "col-lg-3 control-label"})
        <div class="col-lg-9">
            @Html.DropDownListFor(model => model.platform, platformList, new {@class = "form-control", @id = "inputPlatform"})
        </div>
    </div>

    <button type="submit"> Submit</button>
}

控制器

 public class RegisterController : Controller
    {
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegistrationModel model)
        {
            //Do something here;
        }
    }