Delete row in webgrid with checkboxes in MVC3 using Visual Studio 2012 - asp.net-mvc

I am new to MVC3. I have coded an application in which I display data into a webgrid with checkboxes. I am trying to find out how to send a particular row id the controller action method when I click on a checkbox. Any help appreciated.

This all depends on what you are trying to do. Typically, in the view, I will add a data attribute like data-rowid="###" and then use jQuery to capture the .click event. Then in the .click event, retrieve the clicked elements value for data-rowid and call .ajax to post the data to the controller.

This is a complete example where I have a WebGrid with the last column containing a "Remove" link that uses Ajax to call an action on the server. On completion of the Ajax request, the corresponding row is removed from the table. The MvcHtmlString is used to inject a span tag into the column. It contains an id value that is subsequently used to identify the row to be removed from the table.
<div id="ssGrid">
#{
var grid = new WebGrid(canPage: false, canSort: false);
grid.Bind(
source: Model,
columnNames: new[] { "Location", "Number", "Protection", "Methodology" }
);
}
#grid.GetHtml(
tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Location", "Location"),
grid.Column("Number", "Number"),
grid.Column("Protection", "Protection"),
grid.Column("Methodology", "Methodology"),
grid.Column(
format: (item) =>
new MvcHtmlString(string.Format("<span id='ssGrid{0}'>{1}</span>",
item.SecondarySystemId,
#Ajax.RouteLink("Remove",
"Detail", // route name
new { action = "RemoveSecondarySystem", actionId = item.SecondarySystemId },
new AjaxOptions {
OnComplete = "removeRow('ssGrid" + item.SecondarySystemId + "')"
}
)
)
)
)
)
)
</div>
<script>
function removeRow(rowId) {
$("#" + rowId).closest("tr").remove();
}
</script>

Related

ASP.NET: How to get from Dropdownlist to Autocomplete

I have a dropdownlist and want to turn it into autocomplete using jquery.
The dropdown looks like this and works:
#Html.DropDownListFor(m => m.CategoryID, new SelectList(Model.Categories, "ID", "Name", Model.CategoryID), "Categories", new { #class = "form-control" })
I also added an autocomplete field using jquery that works. But so far I can only populate it with dummy data:
$(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp"
];
$("#tags").autocomplete({
source: availableTags
});
});
How can I populate my dropdown field with the data that is available in the dropdown?
Thank you in advance!
You need to set the source as an action method which returns data you want to show as autocomplete option in JSON format.
$(function(){
$("#tags" ).autocomplete({
source: "#Url.Action("SearchCategories","Home")",
minLength: 1,
select: function (event, ui) {
//If you want to do something on the select event, you may do it here
//$("#tags").html(ui.item.label);
}
});
})
Make sure you have an action method called SearchCategories in your HomeController which returns the data you want.
public ActionResult SearchCategories(string term)
{
var db= new MyDbContext();
var results = db.Categories.Where(s => s.Name.StartsWith(term))
.Select(x=>new { id =x.Id,
label =x.Name }).ToList();
return Json(results,JsonRequestBehavior.AllowGet);
}
This should enable the autocomplete on an input with id tags,assuming you have jQuery ui library(and it's dependencies) loaded properly in your page and you do not have any other script errors in your page. I have used Url.Action helper method to generate the correct relative url to the action method. It will work fine if your js code is inside a razor view. But if your code is inside an external js file, you should follow the approach described in this post.

webgrid and partial view issue

i just encounter a code where a person showing how to keep webgrid in partial view and populate. see the link for complete code Bind WebGrid form AJAX
see their partial view code
<!-- Current Buildings -->
#{
if (Model != null && Model.Count() > 0)
{
var grid = new WebGrid(source: Model, rowsPerPage: ThisController.PageSize, ajaxUpdateContainerId: "tabs-2", defaultSort: "BuildingNumber");
grid.Bind(Model, rowCount: Model.Count(), autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
grid.GetHtml(
tableStyle: "display",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("BuildingNumber", header: "Building Number"),
grid.Column("ConstructionDate", header: "Construction Date"),
grid.Column("ExtSquareFeet", header: "Exterior Sq. Ft."),
grid.Column("IntSquareFeet", header: "Interior Sq. Ft."),
grid.Column("IU_Avail", header: "IU Available"),
grid.Column("SpaceAvail", header: "Space Available"),
grid.Column("FixedAssetValue", header: "Fixed Asset Value"),
grid.Column("FixedEquipValue", header: "Fixed Equipment Value")
)
);
}
else
{
#:There are no buildings at this facility.
}
}
but there is no reference for model at top like
#model IEnumerable<MyProject.Models.BuildingModel>
see how partial view understand which model they need to use to populate the webgrid.
see this code to bind webgrid
grid.Bind(Model, rowCount: Model.Count(), autoSortAndPage: false);
here the word model has been used so how web grid know about model because no reference has been added at top of partial view.
in main view they use this code to render partial view
#Html.Partial("_Buildings")
i do not know that model data no need to pass with
#Html.Partial("_Buildings")
or model data automatically pass to partial view.
please help me to understand this. thanks

What is the sequence or flow to implement this view in MVC4

I'm still learning about MVC4.
Imagine the following scenario: I've got three dropDownLists and one big div for the content. I don't know how to deal the loading on demand.
The flow is simple, when page is loaded, display the data in the first dropdownlist. When this one has a value, the second one should load the information on demand (using the selected value from ddl1) and so on, until change the value on the ddl3 and displays the data.
Until here I have detected two partial views. I'm not sure if I should create 5 because each ddl must be in one partial view.
Another thing, what would you recomend to maintain the SelectList, should I have to use ViewBag or maintain in a viewModel the collections foreach ddl?
I just one to know if you can clarrify this scenario. I mean, give an idea about how can I start doing this? In fact, I forgot to mention this doubt but I don't if I have to use AJAX.
I got stuck , few weeks back in same kind of stuff:-
Let your MVC calls be like :-
private void LoadDropdown1()
{
var _data;//Your logic to get the data
ViewData["Dropdown1"] = new SelectList(_data, "Dropdown1Id", "Name");
}
private void LoadDropdown2(int dropdownParameterId)
{
var _data = "";//Use your ID to get the data
ViewData["Dropdown2"] = new SelectList(_data, "Dropdown2Id", "Name");
}
Your .cshtml be :-
#using (Html.BeginForm())
{
<div>
<table>
<tr>
<td><b>Select a District:</b></td>
<td>#Html.DropDownListFor(m => m.Dropdown1Id, ViewData["Dropdown1"] as IEnumerable<SelectListItem>, "Select One", new {#id="Dropdown1Id"})</td>
</tr>
<tr>
<td><b>Select:</b></td>
<td>#Html.DropDownListFor(m => m.Dropdown2Id, ViewData["Dropdown2"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
</table>
</div>
}
Now AJAX call is best to load data to your dropdown:-
$(function () {
$('select#Dropdown1').change(function () {
var id = $(this).val();
$.ajax({
url: 'Bla Bla',
type: 'POST',
data: JSON.stringify({ id: id }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$.each(data, function (key, data) {
$('select#Dropdown1').append('<option value="0">Select One</option>');
// loop through the LoadDropdown1 and fill the dropdown
$.each(data, function (index, item) {
$('select#Dropdown1').append(
'<option value="' + item.Id + '">'
+ item.Name +
'</option>');
});
});
}
});
});
});
What i am trying to say is.. Load your 1st dropdown the way you prefer. Then On change event of 1st dropdown, you can fire an ajax call to fetch data for 2nd dropdown.... Similarly..
Reference:- on select change event - Html.DropDownListFor

Webgrid checkbox selection lost after paging

I have a webgrid
#{
var gdAdminGroup = new WebGrid(source: Model, rowsPerPage: 20, ajaxUpdateContainerId: "tdUserAdminGroup");
}
#gdAdminGroup.GetHtml(
htmlAttributes: new { id = "tdUserAdminGroup" },
tableStyle: "gd",
headerStyle: "gdhead",
rowStyle: "gdrow",
alternatingRowStyle: "gdalt",
columns: gdAdminGroup.Columns(
gdAdminGroup.Column(columnName: "Description", header: "Admin Group"),
gdAdminGroup.Column(header: "", format: #<text><input name="chkUserAdminGroup" type="checkbox" value="#item.AdminGroupID" #(item.HasAdminGroup == 0? null : "checked") /></text>)
)
)
If I check some checkboxs and goes to the second page, the selection on the first page will be lost. Can anyone help me with this? Thank you
The Page selection is links why
- The page is refeshed via a GET command (< a href="...." not < input type="submit" ....)
- The link does not submit form in which you checkbox is in, why you can not read the state of the checkbox.
Either you should look for a JavaScript solution to amend the Checkbox data in the GET URL,
or find another Grid generator.
http://mvccontrib.codeplex.com/wikipage?title=Grid&ProjectName=mvccontrib

How do you get to the underlying data in an MVC3 WebGrid using jQuery?

I have a simple MVC WebGrid. When a user clicks on a row, I'd like to do something based on the row he clicked. Its pretty simple in jqGrid and even using jquery templates, but I'd like to get it right using the MVC WebGrid.
I have the following:
<h2>OrderList</h2>
#{
var grid = new WebGrid(canPage: true, rowsPerPage: 20, canSort: true, ajaxUpdateContainerId: "grid_Orders");
grid.Bind(Model.Orders, rowCount: Model.TotalOrders, autoSortAndPage: true);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(htmlAttributes: new { id = "grid_Orders" },
columns: grid.Columns(
grid.Column(columnName: "OrderNo", header: "Order No"),
grid.Column(columnName: "TotalAmountDisplay", header: "Amount", format:#<div style="text-align:right"> R #item.TotalAmountDisplay</div>, canSort: false)
));
}
and the following jQuery
$(document).ready(function () {
$("#grid_Orders").delegate("tbody tr", "hover", function () {
$(this).css("cursor", "pointer");
$(this).toggleClass("datahighlight");
});
$("#grid_Orders").delegate("tbody tr", "click", function () {
//How do I get the underlying data in this row???
});
});
Unfortunately you will need to use jQuery in order to access each row's html data - there is no rich programming model against it that Im aware of (the beauty of MVC at times as well ha)
The same scenario applies here:
MVC WebGrid - How to programatically get the current page, sort column etc

Resources