Display empty textbox using Html.TextBoxFor on a not-null property in an EF entity

↘锁芯ラ 提交于 2019-11-29 17:16:21

问题


I am using Entity Framework (v4) entities. I have an entity called Car with a Year property of type integer. The Year property does not allow NULL. I have the following in my Create view:

<%= Html.TextBoxFor(model => model.Year) %>

I am required to return a new Car object (due to other requirements) in my HttpGet Create action in the CarController.

Currently, a zero is displayed in the Year textbox because the Year property does not allow NULL. I would like to display an empty textbox in the Create view. How do I do this?


回答1:


Use Html Attributes Overload. In razor it would be:

@Html.TextBoxFor(model => model.Year, new { Value = "" })



回答2:


Try this instead:

Html.TextBox("Year", "")



回答3:


If you are using the strongly typed TextAreaFor helper, then there is no direct way to set a default value. The point of the strongly typed helper is that it binds the text area to a model property and gets the value from there. If you want a default value, then putting in the model would achieve that. You can also just switch to the non-strongly typed TextArea helper. It gives you more a bit more flexibility for cases like this:

   @{
          var defaultValue= "";
        }
    @Html.TextArea("Model.Description", defaultValue, new { Value = "added text", @class = "form-control", @placeholder = "Write a description", @rows = 5 })



回答4:


Try this is you are trying to append to your field or want to modify an existing field with an empty TextBoxFor.

Html.TextBoxFor(model => model.Year, Model.Year="")


来源:https://stackoverflow.com/questions/2703860/display-empty-textbox-using-html-textboxfor-on-a-not-null-property-in-an-ef-enti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!