我在[HttpPost]方法的Dropdownlist上收到以下错误。值正确绑定,这不是问题。但是模型状态始终存在错误。错误是:
从“System.String”类型到“System.Web.Mvc.SelectListItem”类型的参数转换失败,因为类型转换器无法在这些类型之间进行转换。
在我的模型中,我使用以下内容。
public class UploadDocumentViewModel {
[Display(Name = "Document Title")]
public string DocumentTitle { get; set; }
public IEnumerable<SelectListItem> FileType { get; set; }
}
FileTypeViewModel:
public class FileTypeViewModel
{
public string FileTypeId { get; set; }
public string FileTypeDescription { get; set; }
}
在Controller HttpGet
中[HttpGet]
public ActionResult UploadDocument()
{
var fileTypes = iFileTypeRepository.GetFileTypes(); // This is for FileType DropDownlist of values
UploadDocumentViewModel uploadDocumentViewModel = new UploadDocumentViewModel
{
FileType = fileTypes.Select(x => new SelectListItem
{
Text = x.FileTypeDescription,
Value = Convert.ToString(x.FileTypeId)
}).ToList()
};
return View(uploadDocumentViewModel);
}
在[HttpPost]方法
中public ActionResult UploadDocument(FormCollection form,UploadDocumentViewModel uploadDocumentViewModel )
{
//FileTypes
string ddlFileTypeSelectedValue = Convert.ToString(form["FileType"]);
var ddlFileType = iFileTypeRepository.GetFileTypes();
uploadDocumentViewModel.FileType = new SelectList(ddlFileType, "FileTypeId", "FileTypeDescription", ddlFileTypeSelectedValue);
// No Errors, then Submit
if (ModelState.IsValid)
{
-- Redirect to some other View
}
else
{
return View(uploadDocumentViewModel);
}
}
在视图中
@model xxx.Core.Model.UploadDocumentViewModel
@{
ViewBag.Title = "Upload Document";
}
<h2>
Upload Client Document</h2>
@Html.ValidationSummary()
@using (Html.BeginForm("UploadDocument", "Document", "FormMethod.Post"))
{
<div>
<fieldset>
<legend>Upload Client Document</legend>
<div class="editor-label">
@Html.LabelFor(model => model.DocumentTitle)
</div>
<div class="demo">
@Html.TextBoxFor(model => model.DocumentTitle, new { @id = "txtDocumentTitle" })
@Html.ValidationMessageFor(model => model.DocumentTitle)
</div>
<div>
@Html.LabelFor(model => model.FileType)
</div>
<div>
@Html.DropDownListFor(model => model.FileType, Model.FileType, "Please Select", new { @id = "ddlFileType" })
</div>
</fieldset>
</div>
<br />
}
@{Html.EndForm();}
答案 0 :(得分:2)
更改此行
@Html.DropDownListFor(model => model.FileType, Model.FileType, "Please Select", new { @id = "ddlFileType" })
到
@Html.DropDownListFor(model => model.FileTypeId, Model.FileType, "Please Select", new { @id = "ddlFileType" })
并在模型中添加字符串属性FileTypeId
,以便在发布时获得所选项目