I am getting the following error for my Dropdownlist on [HttpPost] Method. The values are binding correctly, that is not a problem. But there is an error in model state all the time. The error is:
The parameter conversion from type 'System.String' to type 'System.Web.Mvc.SelectListItem' failed because no type converter can convert between these types.
In my model I am using the following.
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; }
}
In the 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);
}
In [HttpPost] Method
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);
}
}
In View
@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();}
Change this line
to
And add a string property
FileTypeId
to your model, so that when you post you get the selected item