我曾经有一个用于上传文件的表单并且它工作正常,但令我惊讶的是它不再将HttpPostedFileBase绑定到模型。过了一会儿,我意识到这是因为我改变了
@using (Html.BeginForm("AddDocument", "Documents", FormMethod.Post, new { enctype = "multipart/form-data", @class = "addTab" }))
到
@using (Html.BeginForm("AddDocument", "Documents", FormMethod.Post, new { @id = "addForm", enctype = "multipart/form-data", @class = "addTab" }))
所以我改为(我试图删除id的@但它既不起作用)
@using (Html.BeginForm("AddDocument", "Documents", new {id= "addForm"}, FormMethod.Post, new { enctype = "multipart/form-data", @class = "addTab" }))
它再次起作用。
所以我认为我在很长一段时间内都做错了,我在解决方案中改变了其他形式。但事实证明,如果我使用
@using (Html.BeginForm("Edit", "Events", new {id = "editForm"}, FormMethod.Post, new { @class = "addTab" }))
而不是
@using (Html.BeginForm("AddContact", "Contacts", FormMethod.Post, new { @id = "addForm", @class = "addTab" }))
我无法设置ID(也没有使用其他选项)
我正在尝试用msdn documentation来决定但是我甚至不知道id是应该考虑路由值还是html属性,@是什么用于,有时使用,有时不使用特别是为什么我在多部分情况下失去了绑定
更新
这是视图(我已尝试使用注释掉的代码,结果相同):
@model AddDocumentViewModel
@using (Html.BeginForm("AddDocument", "Documents", new {id= "addForm"}, FormMethod.Post, new { enctype = "multipart/form-data", @class = "addTab" }))
{
@Html.ValidationSummary(true, "Please correct the errors and try again.")
<div id="addDocumentdetails">
<div>
@*<input id="File" type="file" name="File" data-val-required="Please select a file" data-val="true" />*@
@*@Html.ValidationMessage("File")*@
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.File)
<span class="right">@Html.DropDownListFor(m => m.OwnedItemId, Model.Plans, "Not attached to a plan..")</span>
</div>
<div>
@Html.EditorFor(m => m.Description,
new { @class = "addNotes", data_placeholders_focus = "false", placeholder = ViewData.ModelMetadata.Watermark })
@Html.ValidationMessageFor(m => m.Description)
</div>
</div>
<div class="addDEC">
<input class="addDECButton" type="submit" value="Save" />
</div>
}
视图模型:
public class AddDocumentViewModel
{
[Display(Prompt = "Document notes")]
[DataType(DataType.MultilineText)]
[StringLength(500, ErrorMessage = "Must be 500 characters or less")]
public string Description { get; set; }
public int? OwnedItemId { get; set; }
public IEnumerable<SelectListItem> Plans { get; set; }
[Required(ErrorMessage = "Select a file")]
public HttpPostedFileBase File { get; set; }
控制器
[HttpGet]
public ActionResult AddDocument()
{
var partyId = (int)Session["PartyId"];
var viewModel = _createBuilder.Build(partyId);
return PartialView("_AddDocument", viewModel);
}
[HttpPost]
public ActionResult AddDocument(AddDocumentViewModel viewModel)
{
var partyId = (int)Session["PartyId"];
if (ModelState.IsValid)
{
_documentsManager.AddDocument(viewModel, partyId);
if (Request.IsAjaxRequest())
return Json(new { passedValidation = true, action = Url.Action("DocumentList") });
return RedirectToAction("Index");
}
var newViewModel = _createBuilder.Rebuild(viewModel, partyId);
return PartialView("_AddDocument", newViewModel);
}