我是 MVC 的新手,几天来我一直在努力解决这个问题。
当我将表单发回服务器时,这些值始终为空。我尝试过使用模型本身,使用集合/列表,我尝试的最后一种方法是使用 ViewModel。
我要实现的目标是标记用户注册的活动的出席情况。我正在获取正确的出席信息并将它们发送到视图。我将选中复选框以更新布尔值 Attend.Attended。在调试过程中,我会在 Post 操作的开头放置一个断点,并且模型、集合/列表、ViewModel 每次都为空。
楷模:
public class Attend
{
[Key]
public int AttendID { get; set; }
public virtual UserProfile User { get; set; }
public virtual Event Event { get; set; }
public Boolean SignedUp { get; set; }
public Boolean Attended {get; set; }
}
public class Event
{
[Key]
public long EventID { get; set; }
[Required]
[DisplayName("When is this event?")]
public DateTime DateScheduled { get; set; }
public DateTime DateCreated { get; set; }
[DisplayName("Event Category")]
public String Category { get; set; }
[Required]
[DisplayName("Location")]
public String Location { get; set; }
public string Comments { get; set; }
[Required]
[DisplayName("Event Name")]
public string EventName { get; set; }
[Required]
[DisplayName("Event Description")]
public string EventDescription { get; set; }
public virtual ICollection<Attend> Attends { get; set; }
}
控制器:
//
// GET: /Event/Attendance
[HttpGet]
public ActionResult Attendance(long id)
{
try
{
var model = new AttendanceViewModel();
if (db == null)
return HttpNotFound();
if (Request.UrlReferrer != null && Request.UrlReferrer.AbsoluteUri != null)
ViewBag.ReferrerUrl = Request.UrlReferrer.AbsoluteUri;
else
ViewBag.ReferrerUrl = Url.Action("Index");
model.Attending = db.Attends.ToList();
ViewBag.myID = id;
return View(model);
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
return HttpNotFound();
}
}
//
// POST: /Event/Attendance
[HttpPost]
public ActionResult Attendance(AttendanceViewModel Attending, long id)
{
//POST ACTION...
}
看法:
model CottagesOfHope.ViewModels.AttendanceViewModel
@{
ViewBag.Title = "Attendance";
}
<h2>Mark Attendance</h2>
@using (Html.BeginForm())
{
<fieldset>
<legend>Attendance</legend>
<table>
<thead>
<tr>
<th>Name</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
@foreach (var j in Model.Attending)
{
if (j.Event.EventID == ViewBag.myId)
{
<tr>
<td>@j.User.FirstName @j.User.LastName</td>
<td>@Html.EditorFor(model => j.Attended)</td>
</tr>
}
}
</tbody>
</table>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
视图模型:
public class AttendanceViewModel
{
public virtual List<Attend> Attending { get; set; }
}
就像我之前说的,这是我尝试正确绑定数据的最后一种方法。任何帮助将不胜感激。
提前致谢!