My Model fields accepting numbers and empty string :
[DisplayName("Height")]
[RegularExpression (@"^\d*$", ErrorMessage="Height must be a number or left out blank")]
public string Height { get; set; }
[DisplayName("Width")]
[RegularExpression(@"^\d*$", ErrorMessage = "Height must be a number or left out blank")]
public string Width { get; set; }
My view:
<%= Html.LabelFor(x => x.Width) %>:
<%= Html.TextBoxFor(x => x.Width) %>
<%= Html.LabelFor(x => x.Height) %>:
<%= Html.TextBoxFor(x => x.Height) %>
In controller action :
[HttpPost]
public ActionResult Edit(MyModeltype model)
{
model.Width = String.IsNullOrEmpty(model.Width) ? "" : model.Width; //NEEDED?
model.Height = String.IsNullOrEmpty(model.Height) ? "" : model.Height; //NEEDED?
if (ModelState.IsValid)
SaveSettings(model);
return View("SomeView");
}
When I provide empty textboxes, Model.Width and .Height are passed as nulls and ModelState.IsValid is false. I just need to be able to pass the empty string. When omitting the regex attribute, same problem, so its not the regex. Thank you!
Try adding the
DisplayFormatattribute to your model’s properties:This will ensure empty textbox values are not converted to NULL.
Alternatively, you could explicitly define your getters and setters to convert nulls to empty strings: