表单提交时型号为NULL(Model is null when form submitted)

2019-07-17 10:45发布

当我点击提交,该file参数为空。

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; }
}

这里是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>

Answer 1:

它的命名冲突和粘结剂尝试将文件属性FileViewModel对象与文件名绑定,这就是为什么你会得到空。 POST名不区分大小写。

更改:

public ActionResult Create(FileViewModel file)

至:

public ActionResult Create(FileViewModel model)

或任何其他名称



Answer 2:

这解决了我的问题也是如此。 这是我使用了类似的模式,这是类似于我分配张贴的模型太变量的名称。 一旦我整理出来的字段名称的所有工作按预期。

当然,错误是不指出这一点很有帮助。



文章来源: Model is null when form submitted