【发布时间】:2015-09-18 14:10:51
【问题描述】:
这是我的模型;
using System;
using System.ComponentModel.DataAnnotations;
namespace thinkBigHR.Models
{
public class Shift
{
[Key]
public int Id { get; set; }
public DateTime Date { get; set; }
public Employee Employee { get; set; }
}
}
这是我的控制器;
// POST: Shifts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Date, Employee")] Shift shift)
{
ClaimsIdentity user = User.Identity as ClaimsIdentity;
if (user.HasClaim("Administrator", "true"))
{
if (ModelState.IsValid)
{
db.Shifts.Add(shift);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(shift);
}
return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
}
这是我的观点。
@using thinkBigHR.Models;
@model thinkBigHR.Models.Shift
@{
ApplicationDbContext db = new ApplicationDbContext();
ViewBag.Title = "Create";
var employees = db.Employees.ToList();
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Shift</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="datetime-local" class="form-control" id="Date" name="Date" />
@Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Assigned Employee:</label>
<select name="Employee" class="form-control">
@foreach (var item in employees)
{
<option value="@item.Id" id="Employee">@item.LegalName (@item.JobTitle)</option>
}
</select>
</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>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
所以它正确地渲染了视图,但是一旦数据返回到控制器,我就设置了一个断点,它显示只有轮班日期被传回,但没有选择员工的任何细节(返回为空)。
【问题讨论】:
-
您可以将
<select>元素绑定到复杂对象——public Employee Employee { get; set; }就是这样。你需要在你的模型中有一个属性(比如)int Employee并绑定到它。但是为什么你不使用 html 助手@Html.TextBoxFor()和@Html.DropDownListFor()来强绑定到你的模型 -
您使用
employee作为名称,我认为它是一个类或枚举或某个对象。所以为了传递数据你需要指定哪个字段应该包含像employee[0].Id这样的值或创建一些其他属性来传递DDL值
标签: asp.net-mvc