Hi Waghmare,
You need to call stored procedure in controller in that you will get the userId and role as return of stored procedure then you can pass userId and role to switch case.
Refer below article.
And make following changes.
Model
namespace Sample_826807.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class User
{
public int UserId { get; set; }
[Required(ErrorMessage = "Required.")]
public string Username { get; set; }
[Required(ErrorMessage = "Required.")]
public string Password { get; set; }
[Required(ErrorMessage = "Required.")]
[Compare("Password", ErrorMessage = "Passwords do not match.")]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Required.")]
[EmailAddress(ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
public System.DateTime CreatedDate { get; set; }
public Nullable<System.DateTime> LastLoginDate { get; set; }
public Nullable<int> RoleId { get; set; }
public bool RememberMe { get; set; }
}
}
Namespaces
using System.Data;
using System.Web.Mvc;
using System.Web.Security;
using System.Configuration;
using System.Data.SqlClient;
Controller
public class HomeController : Controller
{
// GET: Home
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult Profile()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult Index(User user)
{
int userId = 0;
string role = string.Empty;
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("Validate_User", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", user.Username);
cmd.Parameters.AddWithValue("@Password ", user.Password);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
userId = Convert.ToInt32(sdr["UserId"]);
role = sdr["Roles"].ToString();
}
con.Close();
}
}
string message = string.Empty;
switch (userId)
{
case -1:
message = "Username and/or password is incorrect.";
break;
case -2:
message = "Account has not been activated.";
break;
default:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddMinutes(2880), user.RememberMe, role, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
if (!string.IsNullOrEmpty(Request.Form["ReturnUrl"]))
{
return RedirectToAction(Request.Form["ReturnUrl"].Split('/')[2]);
}
else
{
return RedirectToAction("Profile");
}
}
ViewBag.Message = message;
return View(user);
}
[HttpPost]
[Authorize]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index");
}
}