Observations: @Html.EditorFor and @Html.TextBoxFor in MVC4

Written by stevey on November 24th, 2014

A few tricks learned today when I was working on a email template manager project:

1) If an Action method was marked as [HttpPost] to handle the post event from a form, then there must be a same name Action without [HttpPost] attribute existing in the same controller or you will get a “Page cannot be displayed” error and there was very little debug info to go about.

For example, I have

[ValidateInput(false)]
[HttpPost]
public ActionResult FileUpload(EmailTemplateModel model)
{ //doing files upload }
then I must have a plain action with same name but different signature:

public ActionResult FileUpload()
{
EmailTemplateModel model = new EmailTemplateModel();

model.Attachments= PrepareAttachmentNewModel();

return View(model);

}

or I will get “Page cannot be displayed” error when I try to submit the form with one or multiple “file” html element.

2) Interestingly, when I return the model to view, only when I used @Html.EditorFor, I will be able to render the properties related to the file upload into each textbox; but then the other textboxes will become empty for those fields that were are already there on the form prior to posting the form. Instead, using @Html.TextBoxFor() will retain those values.

Have yet to understand the mechanism underneath, but for now these are my observations and just a quick note first.

 

Leave a Comment