开发者

How do I configure the fields to allow empty strings in my MVC 3 app?

I first designed my database, then used the EF designer to create a model for use in my MVC app. Most of the nvarchar colums in my database have empty strings as defaults, and they do not allow nulls.

How do I configure the fields to allow empty strings in my MVC 3 app?

<div class="editor-label">
  @Html.LabelFor(model => model.Phone2)
</div>开发者_高级运维
<div class="editor-field">
  @Html.EditorFor(model => model.Phone2)
  @Html.ValidationMessageFor(model => model.Phone2)
</div>

The property “Phone2” can be empty, but the default behavior of EF/MVC seems to be to make the field required.

I’ve created a partial class to extend the classes generated by EF, and I also have a MetadataType class to add additional DataAnnotation attributes to the model.

[MetadataType(typeof(MyClassMetadata))]
public partial class MyClass
{
    // Adding more properties and methods here, mostly to support use of enums in EF.
}

public class MyClassMetadata
{
    // Empty strings are ok here!
    public string Phone2 { get; set; }

    [AllowHtml]
    [UIHint("Html")]
    public string Text { get; set; }
}

How do I make a field “not required”? I know I could just skip the validation in my view (use plain controls), but it just seems more “correct” to add the desired behavior to my model instead.


Empty string is allowed by default so you don't need to add any attribute. Moreover:

I could just skip the validation in my view (use plain controls), but it just seems more “correct” to add the desired behavior to my model instead.

That is actually incorrect assumption. It is used in the simplest applications but generally it is considered as a bad practice. ViewModel is responsible for defining validation of user inputs. You can have different validation for edit and insert - how would you achieve that by data annotations on single class?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜