How to pass variables from the Controller to the View in ASP.NET MVC 4.5?

5

I'm pretty familiar with MVC in PHP where I can pass the values to view from the controller as follows:

public function Index(Users user)
{
    return View('index')
        ->with('user', $user);
}

Or to return validation errors:

public function Index()
{
    return View('index')
        ->withErrors(['Erro1', 'Erro2']);
}

How can I do the same in C #? for example, I have the function that receives the E-mail and Password values of a form, it checks if the user exists and if it does not exist, it returns a variable with the error.

[HttpPost]
public void Attempt(string email, string password, Admins db)
{
    Admins admin = db.admins.Where(model => model.email == email).FirstOrDefault(); 

    // return view().with("error", "test1"); ????
}
    
asked by anonymous 24.02.2016 / 17:09

2 answers

2

Usually ViewBag or ViewData is used. What is created in the controller can be accessed in the view.

[HttpPost]
public void Attempt(string email, string password, Admins db) {
    Admins admin = db.admins.Where(model => model.email == email).FirstOrDefault(); 
    ViewBag.Error = "test1"; //ou ViewData["Error"] = "test1";
    return View();
}

view will use this way:

@ViewBag.Error
ou @ViewData["Error"]

More information .

    
24.02.2016 / 17:30
0

The correct way to send Controller validation errors to View is through the ModelState.AddModelError() :

[HttpPost]
public void Attempt(string email, string password, Admins db)
{
    Admins admin = db.admins.FirstOrDefault(model => model.email == email); 

    if (admin == null) 
    {
        ModelState.AddModelError("", "Usuário não é admin.")
    }
}

The dictionary ModelState represents not only the result of all validations involving the request, but also the Model state, the binding of your variables and information about the form. It is populated, in large part, by the pipeline MVC itself, but can also be filled by the programmer, as in this case.

AddModelError also has a form that accepts an exception rather than an error message. The first parameter corresponds to the field name where the validation message should appear (usually combined with jQuery.Validation , which is already installed by default) Filling in the first parameter is optional, since the validation message can refer to the Model integer, as in the example. In this case, you must use @Html.ValidationSummary to display validation messages raised without specific fields.

ViewBag and ViewData are not good choices for validation because they do not have any standardization of data and are not populated automatically by the framework >     

25.08.2016 / 19:58