开发者

auto binding not converting empty string to 0 for int model property

My model object has an int property named SpecialProjectId. That property corresponds to a select box. I am using a default option in the select box. However when I submit the form with the default value the ModelState.isValid keeps being false because the default select option has value="" and for some r开发者_StackOverflow中文版eason the default binder is NOT binding 0 to SpecialProjectId when it finds "" as the value for form field SpecialProjectId. Below is all the code I could think to include. Please help. Note: I am using asp.net mvc 2.0.0 and the System.ComponentModel.DataAnnotations for validation.

//how I am creating the select box

<%= Html.DropDownList("SpecialProjectId", "* Select One *") %>

//what is created by the helper

<select id="SpecialProjectId" name="SpecialProjectId">
<option value="">* Select One *</option>
<option value="1">sp</option>
<option value="3">extra special project</option>
</select>

//my action method

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add([Bind(Exclude="Id, DateAudited")]AuditModel auditModel) {
      try {
          if (!ModelState.IsValid) {                    
                    return View("AuditForm", auditModel);
           }
           //...add audit code...

//my model object

using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Iesi.Collections;

public class AuditModel
{
    public virtual int Id {get; set;}
    //NOT REQUIRED!!!//
    public virtual int SpecialProjectId {get; set;}
    [Required]
    public virtual int AccountId {get; set;}
    [Required]
    public virtual DateTime DateReceived {get; set;} 
}  


This isn't an answer to why "" is not being turned into 0, but a way to avoid that issue in the first place.

//Manually add a "Select One" with value 0 to the SelectList

List<SpecialProject> specialProjectsForSelectBox = new List<SpecialProject>();
specialProjectsForSelectBox.Add(new SpecialProject(0, "* Select One *"));
specialProjectsForSelectBox.AddRange(specialProjectBusinessLogic.FindAllActive());


Why not give the empty option an explicit value of "0"?

EDIT: my bad, I missed that you were creating it with the helper


" NOT binding 0 to SpecialProjectId when it finds "" as the value for form field "

I think this is expected behavior.

Your implicitly telling the model binder to bind this SpecialProjectId to an int. It can't, therefore your model state is invalid.

You want to set your int to a nullable int?. Then your model will be valid.

Think of it as "can't bind" invalid rather than "validation fails" invalid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜