Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model is null when form submitted

Tags:

When I hit submit, the file parameter is null.

public ActionResult Create() {   return View(new FileViewModel()); }  [HttpPost]     [InitializeBlobHelper] public ActionResult Create(FileViewModel file) {   if (ModelState.IsValid)   {      //upload file   }   else     return View(file); }  public class FileViewModel {   internal const string UploadingUserNameKey = "UserName";   internal const string FileNameKey = "FileName";    internal const string Folder = "files";    private readonly Guid guid = Guid.NewGuid();    public string FileName   {     get     {       if (File == null)         return null;       var folder = Folder;       return string.Format("{0}/{1}{2}", folder, guid, Path.GetExtension(File.FileName)).ToLowerInvariant();     }   }    [RequiredValue]   public HttpPostedFileBase File { get; set; } } 

Here is the cshtml:

@model MyProject.Controllers.Admin.FileViewModel  @{   ViewBag.Title = "Create";   Layout = "~/Views/Shared/_BackOfficeLayout.cshtml"; }  @using (Html.BeginForm("Create", "Files", FormMethod.Post, new { enctype = "multipart/form-data" })) {   <fieldset>     <legend>Create</legend>      <div class="editor-label">       @Html.LabelFor(model => model.File)     </div>     <div class="editor-field">       @Html.TextBoxFor(model => model.File, new { type = "file" })       @Html.ValidationMessageFor(model => model.File)     </div>      <p>       <input type="submit" value="Create" />     </p>   </fieldset> }  <div>   @Html.ActionLink("Back to List", "Index") </div> 
like image 318
Shimmy Weitzhandler Avatar asked Dec 20 '12 09:12

Shimmy Weitzhandler


People also ask

How do you deal with null models?

In order to simplify your code you should utilize the Null Object pattern. Instead of using null to represent a non existing value, you use an object initialized to empty/meaningless values. This way you do not need to check in dozens of places for nulls and get NullReferenceExpections in case you miss it.

What is model binding in C#?

Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify.


1 Answers

It's naming conflict and binder trying to bind your File property to FileViewModel object with file name, that's why you get null. POST names are case-insensitive.

Change:

public ActionResult Create(FileViewModel file) 

To:

public ActionResult Create(FileViewModel model) 

or to any other name

like image 107
webdeveloper Avatar answered Dec 27 '22 06:12

webdeveloper