Asp.net MVC4 Dropwdownlist Retain Selected Value after Get - asp.net

I have a drop down list that is included in the _layout view of my application.
What i am trying to do is populate the list with Data from a sql server and then based on the value selected redirect the user to another view.
All is working fine except that when the user click Enter/Search the value of dropdownlist gets defaulted to the first value. As i am currently transitioning from Web Forms it's quite difficult and frustrating.
Here is the code for my Model
public class DomainNameViewModel
{
private static readonly string ConStr = WebConfigurationManager.ConnectionStrings["App"].ConnectionString.ToString();
public string SelectedDomainId { get; set; }
public IEnumerable<SelectListItem> domains
{
get
{
List<SelectListItem> l = new List<SelectListItem>();
using (SqlConnection con = new SqlConnection(ConStr))
{
SqlCommand com = new SqlCommand("spDomainList", con);
con.Open();
SqlDataReader sdr = com.ExecuteReader();
while (sdr.Read())
{
l.Add(new SelectListItem() { Text = sdr[0].ToString(), Value = sdr[1].ToString() });
}
return l;
}
}
The Code for controller.
[ChildActionOnly]
public ActionResult Index()
{
return PartialView(new DomainNameViewModel());
}
The DomainName View
#model app.Models.DomainNameViewModel
#{
Layout = null;
}
#Html.DropDownListFor(x => x.SelectedDomainId, Model.domains, new { #id = "e1",#class = "bannerlist" })
And the code for _Layout view
#using (Html.BeginForm("Search","DomainSearch",FormMethod.Get))
{
#Html.TextBox("txtDomain", null, new { #class = "bannertextbox" , placeholder="Search for a Perfect Domain!" })
#Html.Action("index","DomainName")
<input type="submit" class="bannerbutton" value="Search" />
}
Any help would be appreciated.
EDIT: Added the DomainSearchController code.
public class DomainSearchController : Controller
{
//
// GET: /DomainSearch/
public ActionResult Search(string txtDomain,string SelectedDomainId)
{
DomainNameViewModel Domain = new DomainNameViewModel();
Domain.SelectedDomainId = SelectedDomainId;
string check = Domain.ParseDomain(HttpUtility.HtmlEncode(txtDomain), HttpUtility.HtmlEncode(SelectedDomainId));
string s = Domain.CheckDomains(check);
ViewBag.Domain = Domain.DomainCheckResult(s);
return View();
}
}

You haven't quite shown/explained how exactly are you performing the redirect. But you will need to either pass the selected value in the query string to the target page or store in in a cookie or somewhere on the server like in the ASP.NET Session (beurk).
The reason you need to do this is because in ASP.NET MVC, contrary to classic WebForms there's no ViewState and you cannot retrieve the selected value on subsequent PostBack (there's neither such notion as PostBack in ASP.NET MVC).
Then in your child controller action you will need to retrieve the selected value from the query string or from the cookie or from the ASP.NET session (beurk) and set the SelectedDomainId property on your view model to this value.
For example:
[ChildActionOnly]
public ActionResult Index()
{
var model = new DomainNameViewModel();
// here you need to set the SelectedDomainId property on your view model
// to which the dropdown is bound to the selected value
model.SelectedDomainId = Request["domain_id"];
return PartialView(model);
}
Assuming you decide to pass this value as query string parameter when redirecting you will need to keep this parameter on subsequent redirects in order to keep the state.

Related

Calling multiple model Entity Framework in MVC View

I want to call multiple model in my ADD view. I'm having hard time to call issues model and systems model in one view. See below codes
IssuesController
public ActionResult GetIssues()
{
using(SSD_INTERIM db = new SSD_INTERIM())
{
var issueList = db.TBL_ISSUES.Where(x => x.STATUS != "Closed").ToList();
return Json(new { data = issueList }, JsonRequestBehavior.AllowGet);
}
}
[HttpGet]
public ActionResult GetSystems()
{
using(SSD_INTERIM db = new SSD_INTERIM())
{
var issueList = db.LIB_SSD_SYSTEMS.Where(x => x.ENABLED == "Y").ToList();
return Json(new { data = issueList }, JsonRequestBehavior.AllowGet);
}
}
[HttpGet]
public ActionResult AddOrEdit(int id = 0)
{
return View(new TBL_ISSUES());
}
AddOrEdit.cshtml (view)
#model ProjectName.Models.TLB_ISSUES
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit","Issues", FormMethod.Post, new { onsubmit = "return SubmitForm(this)"}))
{
#Html.HiddenFor(model => model.ISSUE_ID)
<div>
#Html.LabelFor(model => model.SYSTEMNAME, "System", new { #class = "control-label" })
#* Put DropdownListFor for system from different model *#
</div>
<div>
#Html.LabelFor(model => model.ISSUE_DESC, "Description", new { #class = "control-label" })
#Html.EditFor(model => model.ISSUE_DESC, new { htmlAttributes = new {#class="form-control"}})
</div>
}
Screenshot of Entity Framework model
Hope you can help me with my issue, I want to populate system dropdown with datas from different model.
One option is to define a view model for your Add/Edit. I would recommend using a naming convention such as referring to that view as a "Detail" view rather than "AddOrEdit".
[Serializable]
public class IssueDetailViewModel
{
public IssueViewModel Issue { get; set; }
public ICollection<SystemSummaryViewModel> Systems { get; set; } = new List<SystemSummaryViewModel>();
}
[Serializable]
public class IssueViewModel
{
//.. relevant Issue fields matching what you will need to insert/update an Issue entity.
}
[Serializable]
public class SystemSummaryViewModel
{
public int SystemId { get; set; }
public string DisplayName { get; set; }
}
Then populate this model in the case of an Add:
var systems = db.LIB_SSD_SYSTEMS
.Where(x => x.ENABLED == "Y")
.Select(x => new SystemSummaryViewModel
{
SystemId = x.ID,
DisplayName = x.SYSTEMNAME
}).ToList();
var model = new IssueDetailViewModel
{
Issue = new IssueViewModel();
Sytems = systems
};
return View(model);
When you bind the controls in your view, the controls for the Issue use #model.Issue.{property} while your selections for Systems are provided by #model.Systems.
I do not recommend ever passing Entity classes to and from views, but instead get in the practice of defining view models. The model for a view is a separate concern to a data model (which the entity reflects). Passing entities around leads to all kinds of issues including risking exposing far more information about your data implementation than the client needs, sending more data over the wire than the client needs, performance issues arising from serialization and lazy loading, and vague errors occurring when working with detached entity instances. These errors are commonly due to missing data or multiple instances for the same data when deserialized from the client, and can be situational making them appear intermittently or otherwise hard to reproduce.
For larger models with many lookups, or cases where you have larger lookup lists that you'll want to implement something like auto-complete searching to find matches (addresses, etc.) then you'll likely want to look at performing Ajax calls back to the server to load lookups on demand or based on search criteria.

How to do a remote post from controller in ASP.NET Core

I've got a checkout page that is supposed to redirect user to the payment-gateway payment processing page. It expects form data to be posted (Amount, Access_key, Order_id, etc;).
What I've gotten so far is this;
public class OrderController : Controller {
private readonly IOrderService _service;
public OrderController(IOrderService service) {
_service = service;
}
[HttpGet]
public async Task<IActionResult> Index () {
// order processing form
// order model binding code not included for brevity.
return View();
}
[HttpPost]
public async Task<IActionResult> ProcessOrder (OrderModel model) {
var orderId = _service.CreateOrder(model);
// order processing code not included for brevity. (basically create new order and reduce stock)
var dataToPost = new PGData() {
Amount = 10,
Currency = USD,
TxId = orderId,
SuccessUrl = "https://test#domain.com/order/success",
FailedUrl = "https://test#domain.com/order/fail"
Access_Key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
Field_Hash = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
};
// need to redirect user to ("https://pg#pgdomain.com/paynow") with the post data above
}
}
I've found a code snippet that works with .Net Framework but not with .Net Core:
private class RemotePost
{
private NameValueCollection Content = new NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Content.Add(name, value);
}
public void Post()
{
HttpContext.Response.Body.WriteAsync(bytes);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head>");
System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
for (int i = 0; i < Inputs.Keys.Count; i++)
{
System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");
System.Web.HttpContext.Current.Response.End();
}
}
How do I go about achieving this in .Net Core (3.1) in the most secure way as possible?
The ProcessOrder method creates the remote object for external destination (your dataToPost) and returns a view:
return View(dataToPost);
The ProcessOrder.cshtml view accepts a PGData model:
#model PGData
This view contains a form with hidden inputs for each property that needs to be sent to the external destination:
<form name="my-form" method="POST" action="https://pg#pgdomain.com/paynow">
<input type="hidden" asp-for="#Model.Amount"/>
...
</form>
A piece of JavaScript code will submit this form on document load:
window.onload = function(){
document.forms['my-form'].submit();
}
Usually the payment gateways call a callback endpoint in your website and you can check the status of payment and if the data was tampered with.
By the way you need to read the documentation of your gateway endpoint carefully since you're dealing with money here. They usually provide example code for popular web frameworks.

How to get POST data in WebAPI?

I'm sending a request to server in the following form:
http://localhost:12345/api/controller/par1/par2
The request is correctly resolved to a method like:
[HttpPost]
public void object Post(string par1, string par2)
However, I pass additional data through the request content. How can I retrieve these data?
For the sake of example, let's say, that the request is sent from the form:
<form action="http://localhost:12345/api/controller/par1/par2" method="post">
<input type="hidden" name="data" value="value" />
<input type="submit" name="submit" value="Submit" />
</form>
From answer in this question:
How to get Json Post Values with asp.net webapi
Autoparse using parameter binding; note that the dynamic is made up of JToken, hence the .Value accessor.
public void Post([FromBody]dynamic value) {
var x = value.var1.Value; // JToken
}
Read just like Request.RequestUri.ParseQueryString()[key]
public async Task Post() {
dynamic obj = await Request.Content.ReadAsAsync<JObject>();
var y = obj.var1;
}
Same as #2, just not asynchronously (?) so you can use it in a helper method
private T GetPostParam<T>(string key) {
var p = Request.Content.ReadAsAsync<JObject>();
return (T)Convert.ChangeType(p.Result[key], typeof(T)); // example conversion, could be null...
}
Caveat -- expects media-type application/json in order to trigger JsonMediaTypeFormatter handling.
After spending a good bit of time today trying to wrap my brain around the (significant but powerful) paradigm shift between old ways of processing web form data and how it is done with WebAPI, I thought I'd add my 2 cents to this discussion.
What I wanted to do (which is pretty common for web form processing of a POST) is to be able to grab any of the form values I want, in any order. Say like you can do if you have your data in a System.Collections.Specialized.NameValueCollection. But turns out, in WebAPI, the data from a POST comes back at you as a stream. So you can't directly do that.
But there is a cool little class named FormDataCollection (in System.Net.Http.Formatting) and what it will let you do is iterate through your collection once.
So I wrote a simple utility method that will run through the FormDataCollection once and stick all the values into a NameValueCollection. Once this is done, you can jump all around the data to your hearts content.
So in my ApiController derived class, I have a post method like this:
public void Post(FormDataCollection formData)
{
NameValueCollection valueMap = WebAPIUtils.Convert(formData);
... my code that uses the data in the NameValueCollection
}
The Convert method in my static WebAPIUtils class looks like this:
/// <summary>
/// Copy the values contained in the given FormDataCollection into
/// a NameValueCollection instance.
/// </summary>
/// <param name="formDataCollection">The FormDataCollection instance. (required, but can be empty)</param>
/// <returns>The NameValueCollection. Never returned null, but may be empty.</returns>
public static NameValueCollection Convert(FormDataCollection formDataCollection)
{
Validate.IsNotNull("formDataCollection", formDataCollection);
IEnumerator<KeyValuePair<string, string>> pairs = formDataCollection.GetEnumerator();
NameValueCollection collection = new NameValueCollection();
while (pairs.MoveNext())
{
KeyValuePair<string, string> pair = pairs.Current;
collection.Add(pair.Key, pair.Value);
}
return collection;
}
Hope this helps!
I had a problem with sending a request with multiple parameters.
I've solved it by sending a class, with the old parameters as properties.
<form action="http://localhost:12345/api/controller/method" method="post">
<input type="hidden" name="name1" value="value1" />
<input type="hidden" name="name2" value="value2" />
<input type="submit" name="submit" value="Submit" />
</form>
Model class:
public class Model {
public string Name1 { get; set; }
public string Name2 { get; set; }
}
Controller:
public void method(Model m) {
string name = m.Name1;
}
It is hard to handle multiple parameters on the action directly. The better way to do it is to create a view model class. Then you have a single parameter but the parameter contains multiple data properties.
public class MyParameters
{
public string a { get; set; }
public string b { get; set; }
}
public MyController : ApiController
{
public HttpResponseMessage Get([FromUri] MyParameters parameters) { ... }
}
Then you go to:
http://localhost:12345/api/MyController?a=par1&b=par2
Reference: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
If you want to use "/par1/par2", you can register an asp routing rule. eg routeTemplate: "API/{controller}/{action}/{a}/{b}".
See http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
Try this.
public string Post(FormDataCollection form) {
string par1 = form.Get("par1");
// ...
}
It works for me with webapi 2
None of the answers here worked for me. Using FormDataCollection in the post method seems like the right answer but something about my post request was causing webapi to choke. eventually I made it work by including no parameters in the method call and just manually parsing out the form parameters like this.
public HttpResponseMessage FileUpload() {
System.Web.HttpRequest httpRequest = System.Web.HttpContext.Current.Request;
System.Collections.Specialized.NameValueCollection formData = httpRequest.Form;
int ID = Convert.ToInt32(formData["ID"]);
etc
I found for my use case this was much more useful, hopefully it helps someone else that spent time on this answer applying it
public IDictionary<string, object> GetBodyPropsList()
{
var contentType = Request.Content.Headers.ContentType.MediaType;
var requestParams = Request.Content.ReadAsStringAsync().Result;
if (contentType == "application/json")
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, object>>(requestParams);
}
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
Is there a way to handle form post data in a Web Api controller?
The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions's parameter as NameValueCollection:
public void Post(NameValueCollection formData)
{
var value = formData["key"];
}
ON WEB API.
[HttpGet]
[Route("api/Get_EXCUTA_PROCEDURE_IBESVNDACMVDD")]
public IHttpActionResult Get(int CodigoPuxada...)
{
string retornoErro = string.Empty;
try
{
//int codigoPuxada = entrada.CodigoPuxada;
SetKeyAtual(CodigoPuxada);
var repo = new ItemBroker_Dim_Canal_BookRepositorio(ConnectionString);
try
{
var dadosRetorno = repo.ExcuteProcedure_Busca_vbc_(CodigoPuxada,...); // method return object (dataset)
return Ok(dadosRetorno);
}
catch
{
throw;
}
}
catch (Exception ex)
{
retornoErro = ex.Message;
if (ex.InnerException != null)
retornoErro = ex.InnerException.ToString();
}
return Ok(retornoErro);
}
Other projet invoke web api...
(USING RESTSHARP DLL)
RestClient clientHttpPost1 = null;
string dadosVbc123 = string.empty;
clientHttpPost1 = new RestSharp.RestClient($"{urlWebApiAvante}Get_EXCUTA_PROCEDURE_IBESVNDACMVDD?CodigoPuxada=...");
RestSharp.RestRequest request2 = new RestSharp.RestRequest(RestSharp.Method.GET);
request2.RequestFormat = RestSharp.DataFormat.Json;
request2.AddHeader("Content-Type", "application/json;charset=utf-8");
string strAux1 = string.Empty;
request2.Timeout = 180000;
RestSharp.IRestResponse response = clientHttpPost1.Execute(request2);
if ((response != null) && response.StatusCode == System.Net.HttpStatusCode.OK)
{
try
{
var dataObjects = response.Content.ToString().Trim();
dadosVbc123 = dataObjects.ToString().Replace("\t", "");
if (dadosVbc123.Trim() == "{\"IBESVNDACMVDD\":[]}")
dadosVbc123 = string.Empty;
}
...
}
// converting JSON to dataset
string val1 = dadosVbc123.Replace("{\"IBESVNDACMVDD\":", "").Replace("}]}", "}]");
DataTable dtVBC123 = (DataTable)Newtonsoft.Json.JsonConvert.DeserializeObject(val1, (typeof(DataTable)));

How to save the current model when ajax is requesting?

I'm using Ajax in my application to update a view without refresh the webpage.
Can you notice here http://contoso2.azurewebsites.net/Test/DoTest because I'm highlighting the partial view in yellow color.
But the problem is, when I enter data to the items (math problem), when Ajax is requesting, I don't see the changes in the model.
public ActionResult DoTest()
{
List<Worksheet> worksheets = null;
if (Request.IsAjaxRequest())
{
worksheets = Session["Worksheets"] as List<Worksheet>;
return PartialView("_Problems", worksheets[1]);
}
worksheets = new List<Worksheet>()
{
new Worksheet("Addition and Subtraction of absolute values", new List<Problem1>() { ... }),
new Worksheet("Addition and Subtraction of absolute values", new List<Problem1>() { ... })
}
Session["Worksheets"] = worksheets;
return View(worksheets[0]);
}
I'm using a Session to recover my model, but if I debug in it I don't see any changes of the models. How can I do for when I press continue button, my model updates.
EDIT: This contain my AJAX in razor view
#using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "problemList"
}))
{
<input type="submit" value="Continue" />
}
I usually have two Actions for a View . Though this is not a mandatory requirement.
The first action decorated with HttpGet renders the page on a Get when the user comes to the page for the first time. the second action is invoked when the user clicks next and posts a form.
public class TestController {
[HttpGet]
public void DoTest(){
var viewModel = new List<Worksheet>()
{
new Worksheet("Addition and Subtraction of absolute values", new List<Problem1>() { ... }),
new Worksheet("Addition and Subtraction of absolute values", new List<Problem1>() { ... })
};
return View(viewModel);
}
[HttpPost]
public void DoTest(List<Worksheet> worksheets){
//do whatever you want with the user response
var response = worksheets[1];
PartialView("_Problems",responseModel);
}
}
Note : you will have to invoke the ajax call with HttpMethod = "post". The ModelBinder in ASP.NET will bind the values posted in the request to your responseModel worksheets
You should try and go over the "getting-started-with-aspnet-mvc4" tutorials available on http://asp.net/

MVC 3 Authorize custom roles

I am new MVC 3 user and I am trying to make admin through SQL database.
First of all, I have Customer entity and admin can be defined through admin field which is boolean type in Customer entity.
I want to make to access admin only in Product page, not normal customer.
And I want to make [Authorize(Roles="admin")] instead of [Authorize].
However, I don't know how can I make admin role in my code really.
Then in my HomeController, I written this code.
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index(Customer model)
{
if (ModelState.IsValid)
{
//define user whether admin or customer
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString());
String find_admin_query = "SELECT admin FROM Customer WHERE userName = '" + model.userName + "' AND admin ='true'";
SqlCommand cmd = new SqlCommand(find_admin_query, conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
//it defines admin which is true or false
model.admin = sdr.HasRows;
conn.Close();
//if admin is logged in
if (model.admin == true) {
Roles.IsUserInRole(model.userName, "admin"); //Is it right?
if (DAL.UserIsVaild(model.userName, model.password))
{
FormsAuthentication.SetAuthCookie(model.userName, true);
return RedirectToAction("Index", "Product");
}
}
//if customer is logged in
if (model.admin == false) {
if (DAL.UserIsVaild(model.userName, model.password))
{
FormsAuthentication.SetAuthCookie(model.userName, true);
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "The user name or password is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
And DAL class is
public class DAL
{
static SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString());
public static bool UserIsVaild(string userName, string password)
{
bool authenticated = false;
string customer_query = string.Format("SELECT * FROM [Customer] WHERE userName = '{0}' AND password = '{1}'", userName, password);
SqlCommand cmd = new SqlCommand(customer_query, conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
authenticated = sdr.HasRows;
conn.Close();
return (authenticated);
}
}
Finally, I want to make custom [Authorize(Roles="admin")]
[Authorize(Roles="admin")]
public class ProductController : Controller
{
public ViewResult Index()
{
var product = db.Product.Include(a => a.Category);
return View(product.ToList());
}
}
These are my source code now. Do I need to make 'AuthorizeAttribute' class?
If I have to do, how can I make it? Could you explain to me? I cannot understand how to set particular role in my case.
Please help me how can I do. Thanks.
I know this question is a bit old but here's how I did something similar. I created a custom authorization attribute that I used to check if a user had the correct security access:
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
// Get the roles from the Controller action decorated with the attribute e.g.
// [AccessDeniedAuthorize(Roles = MyRoleEnum.UserRole + "," + MyRoleEnum.ReadOnlyRole)]
var requiredRoles = Roles.Split(Convert.ToChar(","));
// Get the highest role a user has, from role provider, db lookup, etc.
// (This depends on your requirements - you could also get all roles for a user and check if they have the correct access)
var highestUserRole = GetHighestUserSecurityRole();
// If running locally bypass the check
if (filterContext.HttpContext.Request.IsLocal) return;
if (!requiredRoles.Any(highestUserRole.Contains))
{
// Redirect to access denied view
filterContext.Result = new ViewResult { ViewName = "AccessDenied" };
}
}
}
Now decorate the Controller with the custom attribute (you can also decorate individual Controller actions):
[AccessDeniedAuthorize(Roles="user")]
public class ProductController : Controller
{
[AccessDeniedAuthorize(Roles="admin")]
public ViewResult Index()
{
var product = db.Product.Include(a => a.Category);
return View(product.ToList());
}
}
Your Role.IsInRole usage isn't correct. Thats what the
[Authorize(Roles="Admin")] is used for, no need to call it.
In your code you are not setting the roles anywhere. If you want to do custom role management you can use your own role provider or store them in the auth token as shown here:
http://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization
note the section:
// Get the stored user-data, in this case, user roles
if (!string.IsNullOrEmpty(ticket.UserData))
{
string userData = ticket.UserData;
string[] roles = userData.Split(',');
//Roles were put in the UserData property in the authentication ticket
//while creating it
HttpContext.Current.User =
new System.Security.Principal.GenericPrincipal(id, roles);
}
}
However an easier approach here is to use the built in membership in asp.net.
Create a new mvc project using the 'internet application' template and this will all be setup for you. In visual studio click on the "asp.net configuration" icon above solution explorer. You can manage roles here and assignment to roles.

Resources