MVC identity changing user roles - asp.net-mvc

I have a Vb.net MVC project with single user authentication. Admins can view all users within a "manager users" page, users are split in to 3 different roles Admin, Employee and User respectively. I want Admins to be able to promote roles: Users to Employee or Employee to Admin, and also demote.
I thought about adding a button next to each user to either promote or demote. I'm struggling as to how each button would be linked to each user and how i would post that one user change back to the controller.
Could someone please advise, thanks
UserViewModels.vb
Public Class GroupedUserViewModel
Public Property Users() As List(Of UserViewModel)
Public Property Admins() As List(Of UserViewModel)
Public Property Employee() As List(Of UserViewModel)
End Class
Public Class UserViewModel
Public Property FullName() As String
Public Property Email() As String
Public Property RoleName() As String
End Class
View:
I'm displaying all Admin, Employee and User roles within the view, here is the admin example:
#Modeltype GroupedUserViewModel
#If Model.Admins.Any Then
#:<div Class="Rtable Rtable--3cols Rtable--collapse">
#For Each Admin In Model.Admins
#:<div Class="Rtable-cell">
#Admin.FullName
#:</div>
#:<div Class="Rtable-cell">
#Admin.Email
#:</div>
#:<div Class="Rtable-cell">
#Admin.RoleName
#:</div>
Next Admin
#:</div>
End If

I'm going to stick with a mostly HTML-based answer, as my VB is rusty. Feel free to substitute the appropriate HTML/URL helpers or whatever you would like.
Basically, you can take one of two approaches:
Have a separate form for each button. This makes the most sense if you also have separate actions for each button (i.e. you have a Promote action and a Demote action on your controller.
<form action="/path/to/promote/action" method="post">
<input type="hidden" name="userId" value="1" />
<button type="submit">Promote</button>
</form>
<form action="/path/to/demote/action" method="post">
<input type="hidden" name="userId" value="1" />
<button type="submit">Demote</button>
</form>
One form with both "Promote" and "Demote" buttons. This obviously makes more sense if you have just one action that will handle both processes.
<form action="/path/to/role/change/action" method="post">
<input type="hidden" name="userId" value="1" />
<button type="submit" name="promote">Promote</button>
<button type="submit" name="demote">Demote</button>
</form>
Then, since only the button that is clicked will be included in the post data, you can branch in your action accordingly:
If Request.Form["promote"] IsNot Nothing Then
'promote user
ElseIf Request.Form["demote"] IsNot Nothing Then
'demote user
EndIf
You could also get fancier and use AJAX to handle this, but this should be enough to get you going.

Related

ASP.NET MVC Remove Model Validations

Let's suppose I have a form with two submit buttons: save and delete.
How can I remove/disable model validations on delete button?
Assuming you're using standard unobtrusive/jQuery validate; Disable client-side validation by putting a class of "cancel" on the button:
<button type="submit" class="cancel">Delete</button>
This will prevent client-side validation from firing at all in the event of this button being clicked.
For server side, just don't check if the model's valid or not.
For example, if you have a property Name on the model and you want NOT to validate it on delete.
You first need to differentiate if the httppost is coming from the save or delete button.
Add to your Model field IsDelete.
I suggest you add in your view something like:
#Html.HiddenFor(x => x.IsDelete)
Add onclick event to your delete button:
<button type="submit" onclick="javacript: $('#IsDelete').val('true');"> Delete </button>
In the controller do something like:
public ActionResult MyAction(MyModel model)
{
if(model.IsDelete)
ModelState.Remove("Name");
var valid = ModelState.IsValid();
}
You can use two separate forms in the view for the edit and delete.
Ex:
#using(Html.BeginForm("Edit", "Employee"))
{
//Edit inputs - ex textboxes for employee details such as name, age...
<input type="submit" value="Edit" />
}
#using(Html.BeginForm("Delete", "Employee"))
{
//Delete inputs - ex: hidden input for employee id
<input type="submit" value="Delete" />
}

How do i create dynamic properties in Model and use in Controller and View. - MVC

I am looking for a solution which creates dynamic properties to be create in Model.
I want to use them in my View and Controller.
Can any one have idea, how to create it?
I am having scenario in my project where one page will be having options to be lets say Profile2, Profile5 etc.
Profile 2 can have two URLs to be submit from user.
Profile 5 can have five URLs to be submit from user.
and
So on........
Is there any solution or alternative to do this????
He Amit , For your situation "I am having scenario in my project where one page will be having options to be lets say Profile2, Profile5 etc.
Profile 2 can have two URLs to be submit from user.
Profile 5 can have five URLs to be submit from use"
You want to put this url in your properties ok.
SO do one thing create a property like this.
public List<string> urlList {get;set;}
use this in your property andd add url in the list.
you can add n no of urls.
That is exactly what ViewBag is for. Its a dynamic property on Controller and View.
public ActionResult SomeAction()
{
ViewBag.Message = "Hello, world";
}
<p>#ViewBag.Message</p>
This will allow you to send anonymous property values from your Controller to your View. However, if you're looking to post different numbers of values (urls in your example), you should use an IList as your model.
#model IList<string>
#for (int i = 0; i < Model.Count; i++)
{
#Html.EditorFor(model => model[i])
}
Your model should probably store the values in a list. Here is an example explaining how to display and save data for a list property.
How to interact with List<t> in MVC
see this is what i have done as an alternative.
Make all divs and other fields in MODEL and use jQuery to work around.
I guess this is an alternative, but not exactly what i want. Still looking for answer. I post this as this can be helpful to some one in future.
Please check below.
<div>
#for (var i = 0; i < ProfileCount; i++)
{
<label>
URL:</label>
<input type="text" id=#string.Format("URL{0}", i) />
<label>
CheckName:</label>
<input type="text" id=#string.Format("URL{0}CheckName", i) />
<label>
Run Check From:</label>
#Html.DropDownList(string.Format("URL{0}Region", i), (IEnumerable<SelectListItem>)ViewBag.Regions)
<br />
<span id=#string.Format("URL{0}Result", i)></span>
<input type="button" value="Create check" id=#string.Format("URL{0}CheckSetup", i) onclick="getResponseFromUrl('#string.Format("URL{0}')", i);" />
<input type="button" value="Delete check" id=#string.Format("URL{0}Delete", i) onclick="DeleteCheck('#string.Format("URL{0}')", i);"
style="display: none" />
<input type="hidden" id=#string.Format("URL{0}Hidden", i) />
<br />
<br />
<br />
}
</div>

MVC File upload validation

I have a simple situation where I have a page that uploads Files, for some importing. At the moment, all I have is a file upload input on my page.
this is what my get controller looks like
public ActionResult FileUpload()
{
return View();
}
This is what my view looks like
#{
ViewBag.Title = "FileUpload";
}
<h2>FileUpload</h2>
<form action="/Home/FileUpload" method="post" enctype="multipart/form-data">
<input type="file" id="newFile" name="newFile" />
<input type="submit" id="submitButton" value="Submit" />
</form>
and this is what my post action looks like
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase newFile)
{
if (newFile.ContentLength > 0)
{
//do stuff here
}
return View("Index");
}
You will of course notice there is no mention of a model here as I cannot find a way to create a model for this situation. I would like to have some very basic validation, along the lines of 'please choose a file before you upload', thats all.
Is there a way to achieve this?!
Thanks in advance
Will
Create model class with string property newFile and put a Required on it.
In controller accept not HttpPostedFile but your model class.
You should add the client side validation manually:
<input type="file" data-val="true" data-val-required="please select a file" name="file" />
#Html.ValidationMessage("file")

How to place two submit buttons in form

I have two submit buttons in one form. I want to call different actions in both buttons. Is there any way to accomplish this without using JavaScript.
Calling different actions is not possible without javascript. You could call the same controller action and inside this action determine which button was pressed using the name property:
<% using (Html.BeginForm()) { %>
<input type="submit" name="save" value="Save" />
<input type="submit" name="update" value="Update" />
<% } %>
and in your controller action:
[HttpPost]
public ActionResult Index(string save)
{
if (!string.IsNullOrEmpty(save))
{
// the save button was pressed
}
else
{
// the update button was pressed
}
return View();
}
Give the buttons different name attributes. Then in your view handler (or equivalent - sorry, not an ASP.NET MVC person), you can check if that button's name is in the HTTP response and act accordingly.
Only one of the submit button names should exist in the response.
Of course there is!
for example, we have following form:
<form>
<input name='customer_name' type='text'/>
<input name='update_user' type='submit' value='Update user info'/>
<input name='delete_user' type='submit' value='Delete user'/>
</form>
when server gets form request there exists only one parameter in the collection: either update_user or delete_user. depends on what user has pressed.

HTML.Listbox in MVC doesn't show up in FormsCollection

I have a ASP.NET MVC application where I have a HTML.Listbox where the user can add items to it, in the webpage. It looks like this.
<p>
<label for="groups">Grupper:</label>
<%= Html.ListBox("RoleGroups", (Model != null ? new SelectList(Model.RoleGroups) : new SelectList(new List<BL.Portal.Domain.Model.RoleGroup>(){})))%>
<%= Html.ValidationMessage("RoleGroups")%>
<br />
<input type="button" id="btnRemoveRoleGroup" name="brnRemoveRoleGroup" value="Ta bort gruppen" />
<input type="button" id="btnAddRoleGrop" name="btnAddRoleGrop" href="#dialogAddRoleGroup" value="Lägg till en grupp" />
</p>
And in the Controller I receive the information like this.
[RequiresRole(RoleToCheckFor = RoleEnum.UserCreate)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateEdit(Model.User user, bool newUser, string confirmedpassword)
But in my User the Properties RoleGroups is always Null so I check the Request.Form.AllKeys and can't find the key: RoleGroups in there. So I guess the information about the Html.Listbox is never sent when I do the postback!
What have I missed?
oooo I must have sleept really bad tonight. There is no problem, what I did, was that I forgott to select the item in the listbox after I have added them to the listbox, so of course nothing was sent in the postback...
Well it's fixed now...

Resources