Associate
- Joined
- 6 Oct 2008
- Posts
- 41
I'm having difficulty trying to get an MVC form to post with valid data.
I have narrowed it down to two dropdownlists on the page.
The values that it binds to in my model page is a boolean.
Code from Model
Code to setup DropDownList from Controller
Code from View
On post the validation fails I guess it is trying to use a string instead of a boolean, can I change the postback value in the ModelState before the page is validated?
Code for Post in Controller
I have narrowed it down to two dropdownlists on the page.
The values that it binds to in my model page is a boolean.
Code from Model
Code:
[Required(ErrorMessage="Please select Yes or No")]
public bool Annonymous { get; set; }
[Required(ErrorMessage="Please select Yes or No")]
public bool TakeFurther { get; set; }
Code to setup DropDownList from Controller
Code:
private void DropDownReBind()
{
List<SelectListItem> SelYN = new List<SelectListItem>();
SelYN.Add(new SelectListItem
{
Text = "Yes",
Value = "1"
});
SelYN.Add(new SelectListItem
{
Text = "No",
Value = "0"
});
ViewData["selYN"] = SelYN;
}
Code from View
Code:
<table>
<tr>
<td class="editor-label">
Would you like to speak to someone from student services?
</td>
<td class="editor-field">
@Html.DropDownListFor(model => model.Annonymous, (IEnumerable<SelectListItem>)ViewData["selYN"], "-- Please Select --")
@Html.ValidationMessageFor(model => model.Annonymous)
</td>
</tr>
<tr>
<td class="editor-label">
Do you want to be contacted to discuss this matter further?
</td>
<td class="editor-field">
@Html.DropDownListFor(model => model.TakeFurther, (IEnumerable<SelectListItem>)ViewData["selYN"], "-- Please Select --")
@Html.ValidationMessageFor(model => model.TakeFurther)
</td>
</tr>
</table>
On post the validation fails I guess it is trying to use a string instead of a boolean, can I change the postback value in the ModelState before the page is validated?
Code for Post in Controller
Code:
[HttpPost]
public ActionResult Create(StudentIncident studentincident)
{
if (ModelState.IsValid)
{
studentincident.ID = Guid.NewGuid();
db.StudentIncidents.Add(studentincident);
db.SaveChanges();
return RedirectToAction("Index");
}
DropDownReBind();
return View(studentincident);
}