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

Asked

Viewed 3,095 times

5

I’m quite used to PHP MVC where I can pass the values to the 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 own the function that receives the E-mail and Password values of a form, checks if the user exists and if it does not exist, 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"); ????
}

2 answers

2


It is usually used ViewBag or ViewData. 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();
}

In the view will use like this:

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

I put in the Github for future reference.

More information.

0

The correct way to send validation errors from Controller to the View is through the command 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 state of the Model, the Binding of its variables and information on the form. It is mostly filled in by the pipeline MVC, but can also be filled by the programmer, as in this case.

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

Viewbag and Viewdata are not good choices for validation because they do not have any data standardization and are not filled automatically by framework

Browser other questions tagged

You are not signed in. Login or sign up in order to post.