0

So, im currently building an application that needs the user model validating, and if the incorrect properties are filled in to the user it will tell them. I have the data annotations set up, but im not sure how i relay the error message back to the user? I have this set up so far on my model and view.

Model

public class DatabaseModel
    {
        [Required(ErrorMessage = ("A first name is required"))]
        public string FirstName { get; set; }
        [Required(ErrorMessage = ("A last name is required"))]
        public string LastName { get; set; }
        [Required(ErrorMessage = ("A valid role is required"))]
        public string Role { get; set; }
        // TODO - Validate rank to only b 1 - 10
        //
        [Range(1,10, ErrorMessage = ("A rank between 1 and 10 is required"))]
        public int Rank { get; set; }      

    }

And View

@model RoleCreatorAndEditor.Models.DatabaseModel
@{
    ViewData["Title"] = "Index";
}

<h2>User Information</h2>

<p>This is your user information!</p>

@using (Html.BeginForm("Index", "Home", FormMethod.Post)) {
    @Html.Label("First Name")
    <br>
    @Html.TextBoxFor(m => m.FirstName)
    <br>
    @Html.Label("Last Name")
    <br>
    @Html.TextBoxFor(m=>m.LastName)
    <br>
    @Html.Label("Role")
    <br>
    @Html.TextBoxFor(m => m.Role)
    <br>
    @Html.Label("Rank")
    <br>
    @Html.TextBoxFor(m => m.Rank)
    <br><br>
    <input type="submit" value="Save">
}

My Controller

public class HomeController : Controller
    {
        // GET: Home
        [HttpGet]
        public ActionResult Index()
        {
            DatabaseModel model = new DatabaseModel();
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(DatabaseModel model)
        {
            if (ModelState.IsValid)
            {
                ListToDatatable convert = new ListToDatatable();
                DataTable user = convert.Convert(model);
                DatabaseRepository dbRepo = new DatabaseRepository();
                dbRepo.Upload(user);
            }
            return View();
        }
    }

I believe the model needs to be passed back to the view in order to display the error message, and although i have read through the documentation on asp.net i cannot understand how they just add the error message and the form knows how to display the errors to the user.

I am extremely confused.

Ryan white
  • 19
  • 8
  • Where is your controller? – SᴇM Oct 27 '16 at 08:43
  • Include `@Html.ValidationMessageFor(m => m.FirstName)` etc in the view (and include the relevant scripts for client side validation. In the controller you also need `if(!ModelState.IsValid) { return View(model); }` –  Oct 27 '16 at 08:44
  • Updating the question now – Ryan white Oct 27 '16 at 08:46
  • Possible duplication of this ticket. http://stackoverflow.com/questions/5739362/modelstate-addmodelerror-how-can-i-add-an-error-that-isnt-for-a-property – karman Oct 27 '16 at 08:50
  • @karman i don't understand the answer to that ticket nor do i understand how to use that on my own problem – Ryan white Oct 27 '16 at 08:51
  • Errors are added by this way. ModelState.AddError method http://stackoverflow.com/questions/5739362/modelstate-addmodelerror-how-can-i-add-an-error-that-isnt-for-a-property – karman Oct 27 '16 at 08:53
  • That still isn't help me understand it, but as @StephenMuecke has explained it to me i understand it better. – Ryan white Oct 27 '16 at 08:54
  • @StephenMuecke thank you for your help – Ryan white Oct 27 '16 at 08:55

1 Answers1

1

You need to use ModelState.IsValid in your Controller and also @Html.ValidationMessageFor(model => model.FirstName) in your view:

public ActionResult Index(ViewModel _Model) 
{ 
    // Checking whether the Form posted is valid one. 
    if(ModelState.IsValid) 
    { 
        // your model is valid here.
        // perform any actions you need to, like database actions,
        // and/or redirecting to other controllers and actions.
    }
    else 
    {
        // redirect to same action
        return View(_Model);
    } 
}

For your example:

@model RoleCreatorAndEditor.Models.DatabaseModel
@{
    ViewData["Title"] = "Index";
}

<h2>User Information</h2>

<p>This is your user information!</p>
@using (Html.BeginForm("Index", "Home", FormMethod.Post)) {
    @Html.LabelFor(m=>m.FirstName)
    <br>
    @Html.TextBoxFor(m => m.FirstName)
    @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })

    <br>
    @Html.LabelFor(m=>m.LastName)
    <br>
    @Html.TextBoxFor(m=>m.LastName)
    @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

    . . .

    <input type="submit" value="Save">
}

Controller:

[HttpPost]
public ActionResult Index(DatabaseModel model)
{
    if (ModelState.IsValid)
    {
        ListToDatatable convert = new ListToDatatable();
        DataTable user = convert.Convert(model);
        DatabaseRepository dbRepo = new DatabaseRepository();
        dbRepo.Upload(user);
    }
    return View(model);
}
Graham
  • 7,431
  • 18
  • 59
  • 84
SᴇM
  • 7,024
  • 3
  • 24
  • 41
  • Sorry i forgot the code to my controller, ill update my question now. – Ryan white Oct 27 '16 at 08:45
  • so i have my model passed into my ccontrolr, and i have the IsValid, but its after this point i get confused – Ryan white Oct 27 '16 at 08:47
  • Not much good without including the relevant `@Html.ValidationMessageFor()` for each property in the view :) –  Oct 27 '16 at 08:47
  • @StephenMuecke so the @html.validationMessageFor(), how exactly do i use this? i do apologize for all the nooby questions, i have never handled MVC before. – Ryan white Oct 27 '16 at 08:49
  • @Ryanwhite - See my comment to your question - you just need one for each property (and use `@Html.LabelFor(m => m.FirstName)` not `Label()`) And use `return View(model);` - always pass a model –  Oct 27 '16 at 08:51