DropDownListFor始终向控制器

时间:2015-06-17 16:16:27

标签: c# asp.net-mvc

我的ViewModel如下所示:

public class ProjectViewModel
    {
        public ICollection<Project> Projects { get; set; }
    }

我的控制器:

    [HttpPost]
    [Route("ChooseProject")]
    public ActionResult ChooseProject(Project projects)
    {
        return RedirectToAction("Index", "Application");
    }

最后我的观点是:

@using ServicePortal.Web.Controllers
@model ServicePortal.Web.Models.ProjectViewModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Choose project";
}

<div class="pure-form pure-form-aligned">
    @using (Html.BeginForm("ChooseProject", "Login", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <div class="innerForm formgroup">
            @Html.ValidationSummary(true, "", new { @class = "" })

            @Html.DropDownListFor((model => model.Projects), new SelectList(Model.Projects,"ProjectKey", "ProjectName"))

            <div class="row">
                <button type="submit" class="button pull-right">Go on</button>,
            </div>
        </div>
    }
</div>

下拉列表中填充了正确的值,但我想将Project或带有ProjectKey的字符串返回给控制器。但是,当我提交表单并检查控制器中参数的值时,它总是为null,当我尝试返回一个Project时和我尝试使用string时。我没有得到任何错误。我做错了什么?

1 个答案:

答案 0 :(得分:2)

试试这个:

public class ProjectViewModel
{
    public string SelectedProjectKey { get; set; }  // string may need to be int depending on what type ProjectKey is in your class
    public ICollection<Project> Projects { get; set; }
}

在视图中:

@Html.DropDownListFor((model => model.SelectedProjectKey), new SelectList(Model.Projects,"ProjectKey", "ProjectName"))

您的控制器操作:

public ActionResult ChooseProject(ProjectViewModel model)

这将为您提供在model.SelectedProjectKey中选择的任何项目的关键,您可以在控制器中使用它选择项目操作方法来执行您想要的任何操作。