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>
}
Related
I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works. I followed different tutorials but not able to solve it. Please take a look and give me the direction.
Thnx in advance.
Controller
public async Task<IActionResult> dashboard(string sortOrder, string SearchString)
{
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(SearchString))
{
movies = movies.Where(s => s.MovieName.Contains(SearchString));
}
switch (sortOrder)
{
case "name_desc":
movies = movies.OrderByDescending(s => s.MovieName);
break;
default:
movies = movies.OrderBy(s => s.MovieName);
break;
}
return View(await movies.AsNoTracking().ToListAsync());
}
public JsonResult AutoComplete(string prefix)
{
var customers = (from movie in this._context.Movie
where movie.MovieName.StartsWith(prefix)
select new
{
label = movie.MovieName,
val = movie.Id
}).ToList();
return Json(customers);
}
dashboard.cshtml
#model IEnumerable<WebApplication1.Models.Movie>
#{
ViewData["Title"] = "dashboard";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Dashboard</h1>
#using (Html.BeginForm())
{
<p>
Find by Movie Name: #Html.TextBox("SearchString")
<input type="hidden" id="hfCustomer" name="Id" />
<input type="submit" value="Search" />
</p>
}
<table class="table">
<thead>
<tr>
<th>
<a asp-action="dashboard" asp-route-sortOrder="#ViewData["NameSortParm"]">#Html.DisplayNameFor(model => model.MovieName)</a>
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.MovieName)
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(function () {
$("#txtMovie").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Movies/AutoComplete/',
data: { "prefix": request.term },
type: "POST",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfCustomer").val(i.item.val);
},
minLength: 1
});
});
</script>
I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works.
Find by Movie Name: #Html.TextBox("SearchString")
If you check the html source code of above TextBox in your browser, you would find it is rendered as below.
The value of id attribute is "SearchString", not "txtMovie". You can try to modify the code to use $("#SearchString") selector, like below.
$("#SearchString").autocomplete({
//...
//code logic here
//...
Test result with testing data
Note: please make sure you add references to required jquery libraries.
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
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
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.
I have been using the code from the article ASP.NET MVC: Ajax Dialog Form Using jQuery UI and it mostly works. I created a grid that lists records and each record has a link to bring up a dialog box to edit the record. After the record has been changed the save button is pressed and the grid is updated using ajax. This works great, but the problem comes after the first record save and the ajax refresh of the grid. If the link to edit the record is clicked again the dialog box doesn't come up, only the partial view is shown. I am guessing, but it appears the partial view that I am trying to bring up again doesn't recognize the parent container. Any ideas?
Display the partial view that contains the grid:
<div id="VehicleHold">
#Html.Partial("_VehicleHold")
</div>
The partial view that makes up the dialog:
#using VehicleWeb.MVCHelpers
#{
int agreementNumber = 0;
var countData = ViewBag.VehicleHoldViewModel as System.Collections.Generic.IEnumerable<VehicleWeb.Model.VehicleHoldViewModel>;
if (countData != null)
{
if (countData.Count() > 0)
{
agreementNumber = (int)countData.DefaultIfEmpty().First().AgreementNumber;
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered">
<thead>
<tr class="table-header">
<th>Edit</th>
<th>Delete</th>
<th>
Type
</th>
<th>
Year
</th>
<th>
Make/Model
</th>
<th>
Plate
</th>
<th>
VIN
</th>
<th>
Num Pass
</th>
</tr>
</thead>
<tbody>
#{
foreach (var item in (ViewBag.VehicleHoldViewModel as System.Collections.Generic.IEnumerable<VehicleWeb.Model.VehicleHoldViewModel>))
{
<tr>
<td>
#Html.ImageDialogLink("UpdateVehicleHold", "Exposure", new { id = item.RID }, "Edit Hold Vehicle", "VehicleHold", Url.Action("RefreshVehicleHold/" + agreementNumber), Html.ResolveUrl("~/pics/edit-button.png"), "Edit Hold Vehicle", "600", "800", new { style = "text-decoration:none;" }, new { style = "text-decoration:none; border-style: none;" })
</td>
<td>
<div title="Vehicle Year">#item.EditType.ToString()</div>
</td>
<td>
<div title="Vehicle Year">#item.AutoYear.ToString()</div>
</td>
<td>
<div title="Vehicle Make/Model">#item.MakeModel.ToString()</div>
</td>
<td>
<div title="Vehicle Plate Number">#item.DistVehNo.ToString()</div>
</td>
<td>
<div title="Vehicle VIN">#item.IDNumber.ToString()</div>
</td>
<td>
<div title="Number Of Passengers">#item.NumOfPassengers.ToString()</div>
</td>
</tr>
}
}
</tbody>
</table>
}
}
}
I am new at asking questions here, so just let me know if you need to see more code.
EDIT:
I don't know if it the position of the jQuery files matters for this. I have been messing around with the position today and haven't found success. I do have the jQuery file on the main form that it used to wire up the dialog box. After the AJAX refreshes the DIV, the edit link seems to loose all knowledge about the any of the parent code. My latest theory is it could be something to do with this code. Could it be because it is in a ready block?
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
// Wire up the click event of any current or future dialog links
$('.dialogLink').on('click', function () {
var element = $(this);
// Retrieve values from the HTML5 data attributes of the link
var dialogTitle = element.attr('data-dialog-title');
var dialogWidth = element.attr('data-dialog-width');
var dialogHeight = element.attr('data-dialog-height');
var updateTargetId = '#' + element.attr('data-update-target-id');
var updateUrl = element.attr('data-update-url');
// Generate a unique id for the dialog div
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = "<div id='" + dialogId + "'></div>";
// Load the form into the dialog div
$(dialogDiv).load(this.href, function () {
$(this).dialog({
modal: true,
resizable: false,
title: dialogTitle,
closeOnEscape: false,
width: dialogWidth,
height: dialogHeight,
buttons: [
{
text: "Save",
icons: { primary: "ui-icon-check" },
click: function () {
// Manually submit the form
var form = $('form', this);
if ($(form).valid()) {
$(form).submit();
$(this).dialog('close');
}
}},
{
text: "Cancel",
icons: { primary: "ui-icon-closethick" },
click: function () {
$(this).dialog('close');
$(this).empty();
}
}]
});
// Enable client side validation
$.validator.unobtrusive.parse(this);
// Setup the ajax submit logic
wireUpForm(this, updateTargetId, updateUrl);
});
return false;
});
});
function wireUpForm(dialog, updateTargetId, updateUrl) {
$('form', dialog).submit(function () {
// Do not submit if the form
// does not pass client side validation
if (!$(this).valid()) {
return false;
}
// Client side validation passed, submit the form
// using the jQuery.ajax form
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
// Check whether the post was successful
if (result.success) {
// Close the dialog
$(dialog).dialog('close');
$(dialog).empty();
// Reload the updated data in the target div
$(updateTargetId).load(updateUrl);
} else {
alert('failure');
// Reload the dialog to show model errors
$(dialog).html(result);
// Enable client side validation
$.validator.unobtrusive.parse(dialog);
// Setup the ajax submit logic
wireUpForm(dialog, updateTargetId, updateUrl);
}
}
});
return false;
});
}
It some times happens when we keep the script in the main view it will bind the event for the first time but won't work after a postback, try moving the script in the partial view, if it doesn't work share some more code and will see what is wrong
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.