Reputation: 18117
I have model
public class UploadOptionModel
{
public UploadOptionModel()
{
OutputFormat = outputFormatList.Select(i => new SelectListItem
{
Text = i,
Value = i
});
}
public string Email { get; set; }
public IEnumerable<SelectListItem> OutputFormat { get; set; }
}
and View
@model PC.Models.UploadOptionModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(p => p.Email)
@Html.DropDownList("OutputFormat", Model.OutputFormat)
}
I am trying to submit the form above using Ajax call and bind it to model
//Calling ValidateFile Action controller
$.ajax({
url: '@Url.Action("ValidateFile", "Converter")',
data: JSON.stringify({ file: fileName, formData: serializedForm }),
contentType: 'application/json',
type: 'POST',
success: function (response) {
if (response.result) {
} else {
RemoveFile(fileName);
}
}
});
function serializeForm() {
var data = $("form").serializeArray();
var formData = {};
for (var i = 0; i < data.length; i++) {
formData[data[i].name] = data[i].value;
}
return formData;
}
The ValidateFile action
[HttpPost]
public JsonResult ValidateFile(string file, UploadOptionModel formData)
{
}
The problem is that UploadOptionModel.OutputFormat
is not binding. I can't read selected dropdown value. UploadOptionModel.Email field is bind successfully.
Upvotes: 0
Views: 1286
Reputation: 2583
You should have another property in your Model class, where you bind the selected value of the dropdownlist. So in your model add something like
public string OutputFormatSelected { get; set; }
And then use it in your view, this way:
@model PC.Models.UploadOptionModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(p => p.Email)
@Html.DropDownListFor( m => m.OutputFormatSelected, m.OutputFormat)
}
Your problem was that you wee binding both the list of elements and the result to the same property
Upvotes: 1