首页 文章

ASP NET MVC 5 SeletList DropDownList

提问于
浏览
0

我在SelectList和DropDownList方面遇到了一些问题 . Ich有两个模型(TimeRecord具有Project的导航属性):

public class Project
{
    public int ProjectId { get; set; }

    [Required]
    public string ProjectName { get; set; }
}

public class TimeRecord
{
    public int TimeRecordId { get; set; }
    public int ProjectId { get; set; }

    public string Description { get; set; }

    public Project TmRecProject { get; set; }
}

在我的Controller中的Create-action方法中,SelectList被ViewBag传递给View(到现在为止一切正常)

public ActionResult Create()
    {
        ViewBag.ProjectId = new SelectList(db.Projects, "ProjectId", "ProjectName");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(TimeRecord timeRecord)
    {
        if (ModelState.IsValid)
        {
            db.TimeRecords.Add(timeRecord);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(timeRecord);
    }

这是视图:

@model SelectListDropDownTest.Models.TimeRecord

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

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

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

    <div class="form-group">
        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
        </div>
    </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>
}

在Create-View中,我可以从DropDownList中选择一个Project . 我的问题是当我将模型“TimeRecord”传递回Controller时,项目“TmRecProject”始终为空 .

解决这个问题的最佳方法是什么?

1 回答

  • 0

    首先,我无法理解您是如何从下拉列表中选择值的,因为您没有将“ViewBag.ProjectId”与下拉列表绑定 . 您的视图和代码中的更改将开始工作!

    Change:

    使用View中的模型绑定下拉列表 .

    @Html.DropDownListFor(model => model.TmRecProject.ProjectId, ViewBag.ProjectId as IEnumerable<SelectListItem>, new { @class = "form-control" })
    

    其他人就是这样,你将获得你的post方法的数据 .

相关问题