Ram
Ram

Reputation: 1141

How to return an error if UserName Password does not match in MVC 4?

i am new to MVC, i want to create a simple Login Control. I have write the below code in controller:

public ActionResult LoginControl(String UserName, String Password)
    {
        string result = "";
        if (UserName == "ram" && Password == "ram123")
        {
            result = "1";
        }
        if (result == "1")
        {
            return View("LoginControl");
        }
        else
        {
            return View("Index", "Login");
        }
    }

Now what i want to do is: if the UserName and password does not match, it will show me error that "UserName or password does not matched or user does not exists.", please help me how can i do it.

Upvotes: 1

Views: 4515

Answers (2)

Your lonely hero
Your lonely hero

Reputation: 11

You could pass your result to the view and than display there. To do this create a TempData key and pass your result there and in the view you can get the value of the tempdata key and than show there.

Here is an example on how to use it: ViewBag, ViewData and TempData

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You could add an error to the ModelState:

else
{
    ModelState.AddModelError("", "Invalid username or password");
    return View("Index", "Login");
}

and then inside the corresponding view use the ValidationSummary helper to display the error:

@Html.ValidationSummary()

Upvotes: 3

Related Questions