简体   繁体   中英

How to display empty required input field in Razr

I have a model that contains some ints. One has a default value and the other does not. I would like to render the input fields with a value 4 for A and an empty value for B . It seems Razr automagically set the default to 0 for my B .

The model

public class MyModel
{
  public int A { get; set; } = 4;
  public int B { get; set; };
}

The controller

// GET /MyModel/Create
public ActionResult Create()
{
  var myModel = new MyModel();
  return View(myModel );
}

The create view

@Html.EditorFor(model => model.A, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.B, new { htmlAttributes = new { @class = "form-control" } })

A renders fine as a 4 but B renders as 0.

I have tried passing @value = "" in the attributes to the editor for B but it still renders as 0.

How can I render B as an empty field? I do not want to make it nullable since it is a required field.

An int cannot be null . If you want to initially display a null (empty) value, but make it required, make the property int? and add a [Required] attribute

[Required(ErrorMessage = "...")]
public int? B { get; set; };

and in the view

@Html.EditorFor(m => m.B, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.B)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM