I have my values in LabelFors but when I do a postback the model has default values.
@using (Html.BeginForm("Delete", "Event", FormMethod.Post))
{
<p>
@Html.LabelFor(m => m.EventID, "Event ID")<br />
@Html.LabelFor(m => m.EventID, Model.EventID.ToString())
</p>
<p>
@Html.LabelFor(m => m.DayCode, "Type of Event")<br />
@Html.LabelFor(m => m.DayCode, Model.DayCode.ToString())
</p>
<p>
@Html.LabelFor(m => m.EventDate, "Date of Event")<br />
@Html.LabelFor(m => m.EventDate, Model.EventDate.ToShortDateString())
</p>
<p>
@Html.LabelFor(m => m.Subject, "Person or Interest")<br />
@Html.LabelFor(m => m.Subject, Model.Subject)
</p>
<p>
@Html.LabelFor(m => m.EventDesc, "Description")<br />
@Html.LabelFor(m => m.EventDesc, Model.EventDesc)
</p>
<table>
<tr>
<td>
@Html.ActionLink("Back", "Index", new { month = Model.EventDate.Month,
year = Model.EventDate.Year,
day = Model.EventDate.Day})
</td>
<td>
<input id="delete" type="submit" value="Submit Changes" />
</td>
</tr>
</table>
}
public ActionResult Delete(int eventID, int year, int month, int day)
{
//Find Event then return to Index
EventModel thisEvent = EventRepository.getDayEvent(eventID, year, month, day);
return View(thisEvent);
}
[HttpPost]
public ActionResult Delete(EventModel deletedEvent) //here Model only has 0, "", and 1/1/0001
{
EventRepository.DeleteEvent(deletedEvent);
return RedirectToAction("Index", new { year = deletedEvent.EventDate.Year, month = deletedEvent.EventDate.Month, day = deletedEvent.EventDate.Day });
}
Your model is empty because your form contains no data. Labels aren’t considered to be data. They are labels for data. What you need is this:
Edit: To make that above part clearer, I should stress that glosrob is right in that you only need the
EventIdin order to process the delete. Everything else is just for displaying the correct information so the user can verify they are deleting the correct record. I just wanted to make the point that labels aren’t considered to be form data, they are a visual indication.There’s a few things to note here though:
Firstly, your
EventIdshouldn’t be open to modification, so it should be rendered with@Html.HiddenFor(m => m.EventId). This will render it as a hidden field which the user will be unable to see. That doesn’t mean it can’t be modified and you should eventually use an AntiForgeryToken to help against that.Secondly, you don’t need to specify the strings for the labels. You can do that on your viewmodel instead with data annotations:
Then in the view you can just use
@Html.LabelFor(m => m.Subject).