asp.net-mvc 表单提交时模型为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13968452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:29:04  来源:igfitidea点击:

Model is null when form submitted

asp.net-mvcformsrazorsubmitform-submit

提问by Shimmy Weitzhandler

When I hit submit, the fileparameter is null.

当我点击提交时,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; }
}

Here is the cshtml:

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

回答by webdeveloper

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.

命名冲突和绑定器试图将您的 File 属性绑定到具有文件名的 FileViewModel 对象,这就是为什么您会得到空值。POST 名称不区分大小写。

Change:

改变:

public ActionResult Create(FileViewModel file)

To:

到:

public ActionResult Create(FileViewModel model)

or to any other name

或任何其他名称

回答by ransems

This solved my issue as well. It was a name that I was using that was similar to the model, which was similar to the variable I assigned the posted model too. once I sorted out the field name all worked as expected.

这也解决了我的问题。这是我使用的一个类似于模型的名称,它也类似于我分配给发布的模型的变量。一旦我整理出字段名称,一切都按预期工作。

Of course the error was not helpful in pointing this out.

当然,错误对指出这一点没有帮助。