I have a view where I display a list of users, setting the model as:
#model List<MyProject.Models.User>
In this view I want to be able to choose to perform an action on a specific user, i.e. post to the controller that I want to disable a user. How do I post the specific User object to the controller?
This is what I've got so far, but I can't see how to post the specific object from the collection:
#foreach (var c in Model)
{
<tr>
<td>#c.Username</td>
<td>#c.IsEnabled</td>
<td>
#using (Html.BeginForm("DisableUser", "UserManagement"))
{
<input type="submit" value="Disable" class="btn btn-primary"/>
}
</td>
</tr>
}
My controller has the signature:
public ActionResult DisableUser(User user)
Rather than posting back all propeties of User, you can just add a route value in the BeginForm() method to post back the ID or the User. Assuming that property is namedUserId`, then
#foreach (var c in Model)
{
<tr>
....
<td>
#using (Html.BeginForm("DisableUser", "UserManagement", new { id = c.UserId ))
{
<input type="submit" value="Disable" class="btn btn-primary"/>
}
</td>
</tr>
}
and the controller method would be
public ActionResult DisableUser(int id)
{
// Get the User based on id, update it and redirect
}
You could also consider using ajax to submit the value, which would allow the user to stay on the same page and continue to 'disable' other User objects without need to make a redirect, in which case the code might be
#foreach (var c in Model)
{
<tr>
....
<td>
<button type="button" class="disable" data-id="#c.UserId">Disable</button>
</td>
</tr>
}
var url = '#Url.Action("DisableUser", "UserManagement")';
$('.disable').click(function() {
var row = $(this).closest('tr');
$.post(url, { id: $(this).data('id') }, function(result) {
if(result) {
// for example, remove the row from the table
row.remove();
} else {
// Oops
}
}).fail(function (result) {
// Oops
});
});
and the controller method would be
public JsonResult DisableUser(int id)
{
// Get the User based on id and update it
return Json(true);
// or if the update failed - return Json(null);
}
The simple way to disable a user is to use a Html.ActionLink instead of the form - you should be able to see plenty of examples of this in the template code. The action link could redirect to a confirmation page or you could just disable the user and redirect to a message page saying "the user has been disabled".
I better way is to use AJAX. You can do this with jQuery or you could use the MVC Ajax form or Ajax Action Link. I would recommend that you google MVC Ajax Action Link examples.
You may also want to style the link by setting it's class to the Bootstrap 'btn' class.
There is a way to post a single user
#foreach (var c in Model)
{
<tr>
<td>#c.Username</td>
<td>#c.IsEnabled</td>
<td>
#using (Html.BeginForm("DisableUser", "UserManagement"))
{
<input type="text" name="Username" value="#c.Username">
<input type="text" name="IsEnabled" value="#c.IsEnabled">
<input type="hidden" name="id" value="#c.id">
<input type="submit" value="Disable" class="btn btn-primary"/>
}
</td>
</tr>
}
The ideas is same,due to lack of time, please proceed according to your requirements, use the Class Property name as input name, the action will get the value
First of all you must not declare Html.BeginForm inside of any loop to post the object to controller.
#using (Html.BeginForm("DisableUser", "UserManagement"))
{
#foreach (var c in Model)
{
<tr>
<td>#c.Username</td>
<td>#c.IsEnabled</td>
<td>
<input data-id="#c.Id" type="submit" value="Disable" class="clsBtnPost btn btn-primary"/>
</td>
</tr>
}
}
This is for your reference
$(document).ready(function(){
$(".clsBtnPost").click(function(){
var userId = $(this).data("id");
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'ControllName/MethodName', //Your Url
data: { 'userId': userId },
success: function () {
alert("successfully called.");
},
failure: function (response) {
alert("Error");
}
});
});
});
You can go with the Ajax Call to pass a single object to controller.
Related
I've developed an asp.net MVC web app where I have a table that shows some items in a model.
I can filter it now with a dropdown list using ajax
The model that i pass to the table is correct (if i go to the model before the foreach there are 3 rows instead of 10 thanks to the filter)
The problem is that the table doesn't change, it always shows all the rows as the initial request.
It look like it works but the table won't update...
There's my jquery ajax call:
$("#Dropdown1Id").on('change', function () {
//console.log("onchange");
//console.log($("#Dropdown1Id").val());
var drpdown1 = $("#Dropdown1Id").val();
var submit = $("#submitButton");
$.ajax({ // crea una chiamata AJAX
data: { data: drpdown1 }, // prendi i dati del form in questo caso del primo dropdown
type: "GET", // GET o POST
url: "/Select/Filter", // li passa al controller
success: function () { // se va con successo esegue il codice seguente
submit.click();
$("#frmId").submit();
},
error: function (error) {
console.log("error")
}
});
});
There's my controller action:
public ActionResult Filter(string data)
{
List<Card> cards = new List<Card>();
ViewBag.stato = new SelectList(myApi.GetState(), "Name", "Name");
if (data != null && data != "")
{
foreach (var card in model)
{
if (card.IdList == data || data == "")
cards.Add(card);
}
return View(cards);
}
return View(model);
}
There's my view with the daple and the dropdown:
#using (Html.BeginForm(new { id = "frmId"}))
{
#Html.AntiForgeryToken()
<table id="tb2">
<tr>
<th>
<h4> LIST : #Html.DropDownList("stato", null, new { #id = "Dropdown1Id" })</h4>
</th>
#*<th>
<h4>ARCHVIED : #Html.DropDownList("closed", null, new { #id = "Dropdown2Id" })</h4>
</th>*#
<th>
<input type="submit" value="Filter" class="btn btn-info" id="submitButton" />
</th>
</tr>
</table>
<br />
<div id="risultato"></div>
<table class="table" id="tb1">
<tr>
<th style="text-align:center">
TRELLO'S CARDS LIST
</th>
<th>LIST</th>
<th>ARCHVIED</th>
<th>Expiration date</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.IdList)
</td>
#if (item.Closed == "True")
{
<td>YES</td>
}
else
{
<td>NO</td>
}
#if (item.Due != null)
{
<td>
#Html.DisplayFor(modelItem => item.Due)
</td>
}
else
{
<td>
Not Present
</td>
}
</tr>
idList.Add(item.Id);
}
</table>
Let me get you through the execution stack and you'll understand why:
Your MVC view is loaded. When the view is returned to the frontend it is already in Html format. Check Server side rendering here
Basically it means that #foreach (var item in Model) will only execute on the server side and will not re-run when you hit an ajax call. This will only happen on a full post.
While in your page you fire up change dropdown event and the following happens:
An ajax call hit your controller
Data are being returned to the success function
Your success: function () is being executed.
A new form post occurs. See that you didn't do anything with the return data that was returned in the success: function(). You just posted back to the controller
After the post, the full view has returned ignoring any changes in the dropdown and in the data returned.
There are 2 solutions for your problem:
Do a full post and return a new view with the proper data
Write some more javascript to change the DOM inside your sucess function
For example: I have to two roles in my application.
1.Administrator // Can perform all CRUD operations on data.
2.Customer // Can only Read the existing data.
In case of returning view to the User according to there role ?
Now I have a choice that create two separate views according to roles.
Let see some Code.
public ActionResult Index()
{
var customers = _dbContext.Customers.Include(c => c.Type).ToList();
if (User.IsInRole(userRole.IsAdministator))
{
return View("Admin_List_View", customers);
} else
{
return View("Customer_ReadOnlyList_View" , customers);
}
}
In the above code.I have two view.
1.Admin_List_View // This view contains all the Data along with Add,Delete,Update,Edit options.
2.Customer_ReadOnly_View // This view will only contains Readonly list.
So my question is that:
In case of simple view i have to follow this approach by writing a separate view for a target roles.
But as it Possible to have a single view and assign the specific section of that to specfic role ?
Note:
I am asking this question is that...In case of complex view that i don't have a choice to create another view from scratch for a particular role. So i am wondering that there is any way to play with the existing view.
For example:
I have to roles.
Admin & customer
and
i have one view.
How to manage that one view for these to roles?
Possible to have a single view and assign the specific section of that to specfic role ?
Yes. You can achieve this with Razor syntax which allows C# in your HTML. Prefix your C# statements with "#". See here.
In your View:
<button>Do Regular User Stuff</button>
#if(User.IsInRole("Admin") {
<button>Do Admin Stuff</button>
}
More Detailed Answer:
public ActionResult Index()
{
var customers = _dbContext.Customers.Include(c => c.Type).ToList();
if (User.IsInRole(userRole.IsAdministator))
{
return View("Admin_List_View", customers);
} else
{
return View("Customer_ReadOnlyList_View" , customers);
}
}
In the above example.
when have two roles and both roles have specfic view.
1.One way is:
to create two view for separate role
for the above example: i had created two views
1.Admin_List_View
2.Customer_ReadOnlyList
2.2nd ways is:
to create sample view and assign html contents based on a user role.
For example:
I have to roles:
again i will say that:
1.AdminList
2.CustomerList.
and now i have only one view:
index.cshtml
index.cshmtl
#model IEnumerable<Vidly.Models.Customer>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 id="heading">Customers</h2>
// This Button is accessible to only admin.
#Html.ActionLink("Add New Customer" , "Add" , "Customer" )
#if (Model.Count() == 0)
{
<p>No Customer is found.</p>
}
else
{
<table id="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Full Name</th>
<th>Email Address</th>
<th>Physical Addrses</th>
<th>Type</th>
<th>Actions</th> // This Column will be only accessible to
admin role.
}
</tr>
</thead>
#foreach (var item in Model)
{
<tbody>
<tr>
<td>#item.FullName</td>
<td>#item.EmailAddress</td>
<td>#item.PhysicalAddress</td>
<td>#item.Type.TypeName</td>
// These Button will be only accessible to Admin
// This is the Edit Button.
<td><button data-customer-id="#item.Id" class="btn btn-link js-delete">Edit</button></td>
// This is the Delete Button.
<td><button data-customer-id="#item.Id" class="btn btn-link js-delete">Delete</button></td>
</tr>
</tbody>
}
</table>
}
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#customers").DataTable();
$("#customers").on("click", ".js-delete", function () {
var button = $(this);
var result = confirm("Are you sure you want to delete this customer?");
function (result) {
if (result) {
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "Delete",
success: function () {
button.parents("tr").remove();
},
error: function (xhr) {
alert("Something goes wrong." + " " + " Error Details " + xhr.status);
}
});
}
});
});
});
</script>
}
So This the entire view.
Now assigning specfic content to specfic Role:
#model IEnumerable<Vidly.Models.Customer>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 id="heading">Customers</h2>
#if(User.IsRole("Admin")) // Checking that if the LoggedIn User is Admin or Not? if The User is Admin Dispay this "Add New Customer Link" Otherwise don't display it.
{
// This Button is accessible to only admin.
#Html.ActionLink("Add New Customer" , "Add" , "Customer" )
}
#if (Model.Count() == 0)
{
<p>No Customer is found.</p>
}
else
{
<table id="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Full Name</th>
<th>Email Address</th>
<th>Physical Addrses</th>
<th>Type</th>
#if(User.IsRole("Admin")) // Again Checking That the User is Admin or not? if the User admin Display the table Header otherwise don't display it.
{
<th>Actions</th> // This Column will be only accessible to admin role.
}
</tr>
</thead>
#foreach (var item in Model)
{
<tbody>
<tr>
<td>#item.FullName</td>
<td>#item.EmailAddress</td>
<td>#item.PhysicalAddress</td>
<td>#item.Type.TypeName</td>
#if(User.IsRole("Admin")) // Checking that the LoggedIn User is Admin or Not. If the User is Admin the Display these buttons otherwise don't Display it.
{
// These Button will be only accessible to Admin
// This is the Edit Button.
<td><button data-customer-id="#item.Id" class="btn btn-link
js-delete">Edit</button></td>
// This is the Delete Button.
<td><button data-customer-id="#item.Id" class="btn btn-link
js-delete">Delete</button></td>
}
</tr>
</tbody>
}
</table>
}
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#customers").DataTable();
$("#customers").on("click", ".js-delete", function () {
var button = $(this);
var result = confirm("Are you sure you want to delete this customer?");
function (result) {
if (result) {
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "Delete",
success: function () {
button.parents("tr").remove();
},
error: function (xhr) {
alert("Something goes wrong." + " " + " Error Details " + xhr.status);
}
});
}
});
});
});
</script>
}
I have a JQuery function that works ok but if I enable [AntiForgerToken] on the Action Method the JQuery function can't access the Action Method, on the view I have other snippet where I enabled AntiForgeryToken:
#using (Html.BeginForm("InsertStudent","Students",FormMethod.Post, new { #id="myform"}))
{
#Html.AntiForgeryToken()
It doesn't matter if the #Html.AntiForgeryToken() inside the view is enabled or not, the JQuery function works good, the one with the problem is at the Action Method...
Why is happening that? What I'm missing?? I've read is very important for security to have [AntiForgeryToken] enabled on the Post Action Methods so I think that the application should work with it enabled in both places the Action Method and the View.
JQuery function:
function InsertShowStudents() {
var counter = 0;
$.ajax({
type:"post",
url: "/Students/InsertStudent/",
data: { Name: $("#Name").val(), LastName: $("#LastName").val(), Age: $("#Age").val() }
}).done(function (result) {
if (counter==0) {
GetStudents();
CounterStudents();
counter = 1;
}
else {
$("#tableJQuery").append("<tr>"+"<td>"+result.Name+"</td>"+"<td>"+result.LastName+"</td>"+"<td>"+result.Age+"</td>"+"</tr>")
}
//clear the form
$("#myform")[0].reset();
}).error(function () {
$("#divGetStudents").html("An error occurred")
})
}
Action method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult InsertStudent(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
//ModelState.Clear();
return RedirectToAction("InsertStudent");
}
return View(student);
}
columns of the table:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Age)
</td>
#* <td style="display:none" class="tdStudentID">#Html.DisplayFor(modelItem => item.StudentID)</td> *#
<td>
<img src="~/images/deleteIcon.png" width="20" height="20" class="imgJQuery" data-id="#item.StudentID" />
</td>
<td>
#Html.ActionLink("Details","Details", new { id=item.StudentID})
</td>
</tr>
}
You not passing the value of the token in your ajax call so an exception is thrown. You can get the value of the token using
var token = $('[name=__RequestVerificationToken]').val();
and modify your ajax call to include it using
data: { __RequestVerificationToken: token, Name: $("#Name").val(), LastName: $("#LastName").val(), Age: $("#Age").val() }
however, it is easier to just serialize your form which will include the token
$.ajax({
type:"post",
url: '#Url.Action("InsertStudent", "Students")', // don't hardcode your url's
data: $('#myform').serialize(),
}).done(function (result) {
Side note: Ajax calls never redirect (the whole point of ajax is to stay on the same page) so having return RedirectToAction("InsertStudent"); in your InsertStudent() will not work. In addition, your returning html, so the $("#tableJQuery").append() code in the .done() callback will fail.
It appears you have a form to add a new Student so your method simply need to return a JsonResult indicating success or otherwise, and if successful, then you can add a new row to your table based on the values in the form, for example
}).done(function (result) {
if (result) {
var row = $('<tr></tr>');
row.append($('<td></td>').text($("#Name").val()));
... // add other cells
$("#tableJQuery").append(row);
//clear the form
$("#myform")[0].reset();
} else {
// Oops something went wrong
}
})
I have a form/view which represents a strongly typed model which contains simple properties and an IEnumerable property. I use an editor template for the IEnumerable property of my model.
for (int i = 0; i < #Model.Items.Count(); i++)
{
#Html.EditorFor(model => #Model.Items[i])
}
Now, the template looks like the following:
#using (Html.BeginCollectionItem("Items"))
{
<table style="width: 100%">
<tr>
<td>
#Html.TextBoxFor(model => #Model.ID, new {id = "ID" })
</td>
<td>
#Html.TextBoxFor(model => #Model.Description, readonly="readonly", new {id = "Description" })
</td>
<tr />
<a role="button" id=getDescBtn>
</a>
</table>
}
And my template's script:
<script type="text/javascript">
$(document).ready(function() {
$("#getDescBtn").on('click', function (event) {
$.ajax({
url: '#Url.Action("LoadDescription")',
async: false,
cache: false,
data: {id: $("#ID").val()}
}).success(function (partialView) {
});
});
});
Now, My controller action looks like:
public ActionResult LoadDescription(string id)
{}
Now, Suppose I have two templates:
In the first one, the ID textbox contains the value of "1".
In the second one, the ID textbox contains the value of "2".
When I press the button in the first template, I get to the controller action twice, both with the value of "1" (from the first template).
When I press the button in the second template, I get to the controller action once, with the value of "1" (from the first template, although I pressed the button of the second template).
Now, what I'm trying to achieve is quite simple logically: press button in first template, get to controller action once with value of "1".
press button in secondtemplate, get to controller action once with value of "2".
Also, the action in controller is responsible to calculate value for description and then fill in the description field. What should the action method return (I don't think I should perform a post for the whole form), and how do I receive it within the success function while using Ajax?
Thanks for any help.
I think you need to use classes for your buttons and editors instead of ids. In your code you have multiple text boxes all with Id=ID and multiple buttons with id=getDescBtn. So $("#ID").val() will just give you the value of the first element with id="ID" which is your first textbox.
As for updating the description, you can have your action return the description value and then set the description text box on the success of your ajax call.
#using (Html.BeginCollectionItem("Items"))
{
<table style="width: 100%">
<tr>
<td>
#Html.TextBoxFor(model => #Model.ID, new {#class = "ID" })
</td>
<td>
#Html.TextBoxFor(model => #Model.Description, readonly="readonly", new {#class = "Description" })
</td>
<tr />
<a role="button" class="getDescBtn">
</a>
</table>
}
<script type="text/javascript">
$(document).ready(function() {
$(".getDescBtn").on('click', function (event) {
$.ajax({
url: '#Url.Action("LoadDescription")',
async: false,
cache: false,
data: {id: $(this).parent().find(".ID").val()}
})
.success(function (data) {
$(this).parent().find(".Description").val(data.description )
});
});
});
public JsonResult LoadDescription(string id)
{
//your logic here
return Json(new {description )});
}
In my web page, I have a series of tables that basically just contain rows of information. Each of these is given an id in a for loop and I'm trying to reference them from outside that. I added classes to both the table and a 'Save Changes' button.
Essentially, my goal is for the user to be able to drag and drop rows around, thereby changing the order. Then they can click the 'Save Changes' button and this will post back to the server with the relevant information.
I am having trouble matching up the button to the relevant table and thereby submitting the id's of each row back to the server in an array. I have written the code to be able to be able to get the ids from each of the tables and their current order, but I don't know how to assign this to an array from within the button click jQuery.
Here is the View:
#foreach (var collection in Model.Collections)
{
<h2>#collection.Season</h2>
#Html.ActionLink("Delete Collection", "DeleteCollection", new { controller = "Edit", brand = collection.Brand.Name, season = collection.Season })
#Html.ActionLink("Edit Collection", "EditCollection", new { controller = "Edit", brand = collection.Brand.Name, season = collection.Season })
#Html.ActionLink("Add Image", "CreateImages", new { controller = "Edit", season = collection.Season })
<p>
To change the ordering of images, drag and drop to your desired position and then click the Save Changes button on the appropriate collection.
</p>
<table class="table-collection" id="table-#collection.Id">
<tr class="nodrop nodrag">
<th>
Id
</th>
<th>
Description
</th>
<th>
Image
</th>
<th>
Options
</th>
</tr>
#foreach (var image in collection.Images)
{
<tr id="#collection.Id-#image.Id">
<td class="dragHandle showDragHandle">
#image.Id
</td>
<td>
#image.Description
</td>
<td>
<img src="#Url.Content("~/" + image.Location)" alt="#image.Description" />
</td>
<td>
<ul>
<li>
#Html.ActionLink("Edit", "EditImage", new { controller = "Edit", brand = image.Collection.Brand.Name,
season = image.Collection.Season, imageId = #image.Id } )
</li>
<li>
#Html.ActionLink("Delete", "DeleteImage", new
{
controller = "Edit",
brand = image.Collection.Brand.Name,
season = image.Collection.Season,
imageId = #image.Id
})
</li>
</ul>
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Save Changes" class="save-order" id="saveTable-#collection.Id"/>
</p>
}
Here is the jQuery so far:
$(document).ready(function () {
$(".table-collection").tableDnD();
$(".save-order").click(function (e) {
e.preventDefault();
$.ajax({ url: window.location.href,
type: 'POST',
data: { ids: $("--ASSIGN ARRAY HERE--"
});
The jQuery to iterate through each row is essentially this:
function(table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Row dropped was "+row.id+". New order: ";
for (var i=0; i<rows.length; i++) {
debugStr += rows[i].id+" ";
}
I see you are using input type submit which is exclusively used to postback forms. What you need to do is wrap every table up in a form with something like this:
#using(Html.BeginForm("Action", "Controller", new{ collectionId = collection.Id }))
{
<input type="submit" value="Save Changes" class="save-order" />
}
Note that this will cause a 'post-back' of the form to Action, Controller. Specify the collection id inside the route values to identify the specific collection.
Do note, you need to add input type hidden with the id's value otherwise the ids' won't get serialised - all you have to specify is the name attribute
<td class="dragHandle showDragHandle">
<input type="hidden" name="ids" value="#(image.Id)" />
#image.Id
</td>
Then you can intercept the call then do it via ajax with:
$(".save-order").click(function(e) {
e.preventDefault();
var form = $(this).closest('form');
if(form.validate()) {
$.post(form.attr('action'), form.serialize(), function() {
alert('The new image order has been saved.');
});
}
return false;
});
The accepting controller action method will probably have this signature
public ActionResult Action(int collectionId, int[] ids)
{
//Do stuff here
return Request.IsAjaxRequest() ? null : View();
}
Now it should support graceful degradation if javascript is disabled (does a normal form submit, otherwise does it via ajax)
Hope this helps :)
You can grab all of the IDs with something like this:
var IDs = [];
$("#mydiv").find("span").each(function(){ IDs.push(this.id); });
In your scenerio, do something like this:
$(document).ready(function ()
{
$(".table-collection").tableDnD();
$(".save-order").click(function (e)
{
var IDs = [];
$("#yourtable").find("draggable-tr-class").each(function(){ IDs.push(this.id); });
e.preventDefault();
$.ajax(
{
url: window.location.href,
type: 'POST',
data: { ids: IDs }
);
}
})
i have been create demo in jsfiddle using json
http://jsfiddle.net/viyancs/4ffb3/11/
if you use like that demo in your server must be get parameter `JSONFile' after that parse this json for what do you want.actually the demo not same with your case but i think you can use this by your logic.