I have an MVC project.
This project has the HomeController
with the action Insert
.
Insert()
takes in model Model
.
The problem is that when submitting the form on the client side ModelState.IsValid
is false
when I don't fill in the non-required field ReportedCount
.
When leaving the field blank, the code automatically picks it up as 0 because it is an int. I've tried manipulating this to a different number during debug but ModelState.IsValid
does not change.
I know that the error happens just with the ReportedCount
field. When I go into ModelState
during debug, the only key that has the error is ReportedCount
. So, of course I go ahead and re-submit the form with the field populated with a number and in that case it is accepted (IsValid = true).
Here is the model:
public class Model
{
[Required(ErrorMessage = "ID field is required.")]
public string ID { get; set; }
[Range(0, 100000, ErrorMessage = "Invalid Number")]
public int ReportedCount { get; set; }
[Required]
public string UserName { get; set; }
}
Here is the controller action:
[HttpPost]
public ActionResult Insert(Model model)
{
bool insert = false;
if (ModelState.IsValid)
{
insert = Service.Insert(model);
}
// If information was inserted properly.
if (insert == true)
{
TempData["message"] = "<b>Input successful :</b> Data entered for id " + model.ID;
TempData["success"] = "true";
}
else
{
// System error has priority to be displayed first.
if (DatabaseError != null)
{
TempData["message"] = DatabaseError;
TempData["success"] = "false";
}
else
{
// Create element showing Model errors.
string message = "";
message = message + "<b>There was an error inserting your data.</b> <ul>";
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
message = message + "<li>" + error.ErrorMessage + "</li>";
}
}
message = message + DatabaseError + "</ul>";
TempData["message"] = message;
TempData["success"] = "false";
}
}
return RedirectToAction("Index");
}
And the html code for the inputs (View):
<html>
<div class='form-group required'>
<label class='control-label'>ID</label>
<select name="ID" class='form-control required' id="DD_ID" required>
<option value="">Select ID</option>
</select>
</div>
<div class='form-group'>
<label class='control-label'>Reported Count</label>
<input class='form-control' type='number' name="ReportedCount">
</div>
<div class='form-row'>
<input class='form-control' id='username' type='hidden' name="UserName" value="@(ViewBag.UserName)" />
</div>
</html>