我是MVC的新手,我一直在爲這個問題奮鬥了幾天。
當我將表單發回服務器時,這些值始終爲空。我嘗試過使用模型本身,使用集合/列表,而我嘗試的最後一種方法是使用ViewModel。
我試圖實現的目標是標記用戶註冊的事件出席。我抓住正確的Attend信息並將它們發送到視圖。我將選中複選框以更新布爾值Attend.Attended。在調試過程中,我會在Post操作開始時放置一個斷點,並且模型,集合/列表,ViewModel每次都爲空。
型號:ViewModel在HTTPPost上爲空
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; }
}
就像我之前說的,這是我嘗試正確綁定數據的最後一種方法。任何幫助將不勝感激。
在此先感謝!
一個同學和我其實弄明白。你的解決方案很有意義,但實際上並沒有幫助。即使我沒有輸入這些參數,它仍然會去那個ActionResult。我不確定是否因爲我的HttpGet使用了相同的操作和控制器,它只是假設它。儘管感謝您的輸入。 – ClinsterMeister