Working on my first ASP.NET MVC application and having some form validation issue.
I have my model:
public class InfoFormEmplModel
{
public int supID { get; set; }
public string description { get; set; }
public InfoFormEmplModel() {}
}
Note that this model doesn't represent any table in my databse.
Now, in my view:
@using Portal.Models
@model InfoFormEmplModel
@{
ViewBag.Title = "Form";
}
@using (Html.BeginForm())
{
<b>Sup</b> @Html.TextBoxFor(x => x.supID)
<p>Description</p>
@Html.TextAreaFor(x => x.description)<br><br>
<input type="submit" name="Save" value="Soumettre" />
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
I need to make some validation, the fields must not be empty and I also have to check if the supId provided exists in my database (server side validation)
I tried to add some validation to my model:
public class InfoFormEmplModel
{
[Required (ErrorMessage = "Superior ID required")]
public int supID { get; set; }
[Required (ErrorMessage = "Description required")]
public string description { get; set; }
public InfoFormEmplModel() {}
}
and also added @Html.ValidationMessageFor to my view:
@using Portal.Models
@model InfoFormEmplModel
@{
ViewBag.Title = "Form";
}
@using (Html.BeginForm())
{
<b>Sup</b> @Html.TextBoxFor(x => x.supID)
@Html.ValidationMessageFor(x => x.supID)
<p>Description</p>
@Html.TextAreaFor(x => x.description)<br><br>
@Html.ValidationMessageFor(x => x.description)
<input type="submit" name="Save" value="Soumettre" />
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
My controller looks like this:
[HttpPost]
public PartialViewResult invform(InfoFormEmplModel form)
{
//check if supID exists
bool exists = librairie.supExists(form.supID);
if (!exists)
{
return PartialView("ErreurDuplicat");
}
return PartialView("Success");
}
When I leave supID empty, the validation doesn't seem to occur..My controller sends my model to another class that check if the superieur Id is in the DB but supID doesn't have any value. I was expecting that before the controller proceeds, I would see the error message on the web page..
Also, once I checked if the supID exists in the DB, how can I display an error message in my view so the user can enter a valid supID?
@model InfoFormulaireEmployeModele.jquery{version}.js?