开发者

Empty drop-down list validation in asp.net mvc

I have a page with 2 forms on it. One of them has a drop-down list on it:

<form ...>

<%: Html.DropDownListFor(x => Model.NewForm.FormId, Model.Forms)%>

<%: Html.ValidationMessageFor(x => Model.NewForm.FormId, "*")%>

<input type="submit" value="Add" />
</form>

The Model's NewForm property is:

public class AddFormViewModel
{
    [Required]
    [DisplayName("Form Id:")]
    public int? FormId { get; set; }
}

I've noticed that when the drop-down list is empty, the 'form' argument is always null and ModelState is always valid.

[HttpPost]
public ActionResult AddForm([Bind(Prefix="NewForm")]AddFormViewModel form)
{
    if (ModelSt开发者_运维问答ate.IsValid)
    {
      ... save
    }
    else
    {
        ... show validation error
    }

    return ...
}

When drop-down list is not empty, everything works as expected, 'form' is not null.

Drop-down list's value is not send when it is empty, this is the default behavior, but anyway, how to make validation work?

Some ideas:

1) I can add a property to view model which will be a hidden input on page just to make model binder work;

2) Custom model binder

What are your ideas?


How about

[HttpPost]
public ActionResult AddForm(AddFormViewModel form)
{
    if (form!= null && ModelState.IsValid)
    {
      ... save
    }
    else
    {
        ... show validation error
    }

    return ...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜