0
  • I am using a simple MVC 4 application using Entity Framework.

    • In my View I am displaying data from of a table using webgrid.
    • View Also has Textboxes(EditorFor) for saving any new record in the table.
    • I am using partial view for the Textboxes, as in the beginning when the page is launched, the textboxes should remain empty.
    • Out of 5, two columns are of integer types.
    • In order to make the textboxes empty initially I am using a new object as -

      @if (!dataGrid.HasSelection) {
      Datamodel = new EntityFrDemo.Models.FacultyDetails { DepartmentID = 0, Name = "", Subject = "", YrsExp = 0, Email = "" };

      Html.RenderPartial("~/Views/Shared/_FacultyDetails.cshtml", Datamodel); }

      //------------------------------------------------------------------------

    @Html.LabelFor(model => model.DepartmentID) @Html.EditorFor(model => model.DepartmentID) @Html.ValidationMessageFor(model => model.DepartmentID)

    //----------------------------------------------------------------------------- enter image description here

    • So I am able to make my boxes empty, however for the Integer type boxes '0' is coming, as I can only assign zero.

So How can I override/superimpose the integer value type boxes to empty string type so that boxes remains empty only in case when no row is selected i.e. in initial stage...?

3
  • 1
    It sounds like you should be using int? instead of int. Commented Jul 9, 2015 at 21:14
  • No, I can't use that, because the Entity Framework has already created 'DepartmentID' as of type integer in the auto generated Entitiy class. I tried using that but it gives casting error of type int? to int. Commented Jul 9, 2015 at 21:19
  • 1
    Then create a viewmodel... Commented Jul 9, 2015 at 22:34

1 Answer 1

1

When you use @Html.EditorFor() with a int value, Razor generate a html tag like this

<input type="number" name="propertyName" id="propertyName" value="propertyValue" />

If you didn't set a value for the int property, the default int value is zero. To set another value in the html tag, you can write it without Razor or you can set the value like the code below.

@Html.EditorFor(model => model.DepartmentID, new { htmlAttributes = new { @Value = "" } })

Note: It is capital "V", not a lower case "v".

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but it did not work. It will be better to create a ViewModel.
@Zeeshaan Didn't Work? Did you get a error message? Or the textbox still render with zero?
Can you copy and paste the Razor sintax here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.