这应该是直截了当的,但是在这里 - 我们正在使用 MVC4 处理多部分表单请求,以通过 MVC4 中的强类型视图上传二进制文件和一些元数据。
其中一个字段是文件的版本号(例如0.0.6、0.4.5-pre等...)
当模型绑定器尝试将此版本号字段绑定到模型字段(字符串类型)时,我从模型绑定器中收到以下错误:
{“从类型 'System.String' 到类型 'Models.NewFileVersion' 的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。”}
具体来说,错误可以追溯到我们的“VersionNumber”字段——关于为什么会发生这种情况的任何想法?
编辑:下面的源代码
新文件版本.cs
public class NewFileVersion
{
[Display(Name = "Version # (0.67, 0.66-pre, etc...)")]
[Required]
public string Version { get; set; }
[Required]
[StringLength(2000, ErrorMessage = "ChangeLog must be between 30 an 2000 characters", MinimumLength = 30)]
[Display(Name = "Version Notes (will be visible to end-users)")]
[DataType(DataType.MultilineText)]
public string ChangeLog { get; set; }
[Display(Name = "Target Platform")]
[UIHint("Enum")]
public FileType PlatformTarget { get; set; }
}
新建.cshtml
@model ViewModels.NewFileVersion
@{
ViewBag.Title = "New";
}
<div class="container" id="main-content">
<div class="row">
<h2>
New</h2>
@using (Html.BeginForm("Create", "Files", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>NewFileVersion</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Version)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Version)
@Html.ValidationMessageFor(model => model.Version)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ChangeLog)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ChangeLog)
@Html.ValidationMessageFor(model => model.ChangeLog)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PlatformTarget)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PlatformTarget)
</div>
<div class="editor-label">
<label for="">
File:</label></div>
<div class="editor-field">
<input type="file" name="fileData" required="required" /></div>
<p>
<input type="submit" value="Upload File" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
文件控制器.cs
[HttpPost]
public ActionResult Create(NewFileVersion version, HttpPostedFileBase fileData)
{
//if our model is valid
if(ModelState.IsValid)
{
//etc....
}
ModelState.AddModelError("", "Invalid file submission");
return View("New", version);
}