Delete webgrid row using javascript? - c#

I have a webgrid in mvc3. It has the column delete. Upon clicking it, I want to run a Javascript function to redirect the user to a controller's action by passing a row id as the parameter to the Javascript function.
How would I do this? The column is not an Htmlactionlink.

Assuming this is the way you have the rows:-
<tr id="thisRowId">
.
.
.
<td>
<a id="deleteBtn" data-rowId="thisRowId">delete</a>
</td>
<tr>
Have a generic function for your delete click
$('#deleteBtn').click(function(){
var id = $(this).data('rowId'); // or use $(this).closest('tr').attr('id');
$.ajax({
url: "controller/action",
type: 'Delete', // assuming your action is marked with HttpDelete Attribute or do not need this option if action is marked with HttpGet attribute
data: {'id' : "'" + id "'"} // pass in id here
success : yoursuccessfunction
});
};

As documented here, this is an example of removing a table row from a WebGrid following an AJAX request. WebGrid doesn't make it easy to identify a particular item in the table. The issue is how to identify the row to be deleted. In the example, 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" }
);
}
#grid.GetHtml(
tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Location", "Location"),
grid.Column("Number", "Number"),
grid.Column(
format: (item) =>
new MvcHtmlString(string.Format("<span id='ssGrid{0}'>{1}</span>",
item.SecondarySystemId,
#Ajax.RouteLink("Delete",
"Detail", // route name
new { action = "DeleteSecondarySystem", actionId = item.SecondarySystemId },
new AjaxOptions {
OnComplete = "removeRow('ssGrid" + item.SecondarySystemId + "')"
}
)
)
)
)
)
)
</div>
<script>
function removeRow(rowId) {
$("#" + rowId).closest("tr").remove();
}
</script>

You can try attaching a jQuery click handler to the element like so:
HTML:
<tr>
<td>
<a id="your id">delete</a>
</td>
<tr>
Javascript:
$("tr a").click(function() {
//your code
});

Related

ASP.NET MVC- How to pass data to another view

In View:
<table>
#foreach(String key in map.Keys)
{
<tr>
<td>
#key
<td>
<tr>
}
<table>
How can I pass the value of key to page2 and retrieve it in page2?
You can add values to the query string using an overload of Url.Action:
Url.Action("page2", "page1", new { key = key })
This would add the value of key to the URL query string, denoted by the key "key".
Besides using passing value with Url.Action, You can also use Html.ActionLink.
#Html.ActionLink("some text here", "actionName", "controllerName", new { id = "1" }, null)
It gives you a link like the following.
some text here

How can I pass multiple parameters to Actionlink() while working with entity framework on c#/html

In my project i am working with MVC design and using the database with Entity Framework.
I wanted to update some cells in my database, but I am not sure how to pass them to the controller to update.
On the Update View page, the user can change the content of the cells using
<td>
<div contenteditable>
#Html.DisplayFor(Model => Model.HeadLine)
</td>
But when I try to send the updated data to the controller I can only understand how to send an id for the Model(because I cannot pass the Model itself).
I am not sure what I am doing wrong - here I am trying to pass an ID so the controller would know what to change and the new name - I get a compilation error.
<p>
#Html.Action("Update This Post >>", "Update", new { param1 = Model.ID, param2 = Model.Author });
</p>
The controller signature is :
[HttpPost]
public ActionResult Update(int id, string author)
Try this :
<p>
#Html.ActionLink("Update This Post >>","YourController", "Update", new { id = Model.ID, author = Model.Author });
</p>
This eventually solved the problem -
https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/examining-the-edit-methods-and-edit-view
I am not sure whether you are trying to pass a reference type or value type variables in the action. you should not pass the reference type but the value types for the anonymous object to pass route parameters. Can you try the below code
#Html.ActionLink("Update This Post >>", "Update", new { id= Model.ID, author= Model.Author });

Unable to print data in grid

I am trying to print my data coming from controller in a table but unable to do so. I am using Kendo UI template in order to print. I am attaching the code below along with the error that I am getting.
<div id="example"></div>
<script>
$.ajax(
{
type: 'POST',
url: '/default1/KendoDataAjaxHandle/',
dataType: 'json',
success: function (result) {
//Get the external template definition using a jQuery selector
var template = kendo.template($("#javascriptTemplate").html());
console.log(result);
var data = template(result); //Execute the template
$("#example").html(data); //Append the result
}
})
</script>
<script id="javascriptTemplate" type="text/x-kendo-template">
<table>
<thead>
<tr>
<th>Customer ID</th>
<th>Customer name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
# for (var i=0; i < result.length; i++){ #
<tr>
# for (var j=0; j < result[i].length; j++){ #
<td>
#= result[j] #
</td>
# } #
</tr>
# } #
</tbody>
</table>
</script>
What i am doing in the above code is making an ajax call to the action method and getting the results in JSON. Here's my controller method:
public ActionResult KendoDataAjaxHandle([DataSourceRequest]DataSourceRequest request)
{
IQueryable<Customer> products = db.Customers;
DataSourceResult result = products.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
Error that I am getting on executing the code is: result is undefined. However on consoling the results returned after ajax call, I get an object which has all the values.
How do I print those values coming back in the table? Also please correct me if I have done something wrong here. Thank in advance.
Try changing the the variable name referenced inside the template from "result" to "data" as that is what Kendo uses in its template execution code.
Example: http://dojo.telerik.com/#Stephen/ENUze
Updated Example
Showing how to iterate the object's fields(based on comment):
http://dojo.telerik.com/#Stephen/oXOJU
NOTE: this assumes that the fields are listed in the order you have specified in your comment. If the fields don't come back in this order, you will have to add code to map the field name to the column index instead of just blindly looping.
Update 2:
Updated example using exact format of returned data:
http://dojo.telerik.com/#Stephen/ipeHec
Note: you have to deal with the CustomerAltID that is in the returned data but not in the table somehow. My example chooses to remove it from list of keys to process. How you deal with it is up to you.

find the records based on search using javascript?

I wrote the below code for finding the records in a table grid.
$(function () {
grid = $('#tblsearchresult');
// handle search fields key up event
$('#search-term').keyup(function (e) {
text = $(this).val(); // grab search term
if (text.length > 1) {
// iterate through all grid rows
grid.find('tr').each(function (i) {
if ($(this).find('td:eq(1)').text().toUpperCase().match(text.toUpperCase()))
$(this).css({ background: "#A4D3EE" });
});
}
else {
grid.find('tr:has(td)').css({ background: "" });
grid.find('tr').show();
} // if no matching name is found, show all rows
});
});
<table id="tblsearchresult" class="tablesorter"">
<thead>
<tr>
<th>ApplicationName</th>
</tr>
</thead>
<tbody>
<% foreach (var request in Model.ApplicationRoles)
{ %>
<tr>
<td>
<span id="appName_<%: request.Id%>">
<%: request.Application.Name%></span>
</td>
</tr>
</tbody>
</table>
EDIT Table Data
applicationame role
application1 appadministrator
app developer
application2 tester
if i given 'app'as search text need to highlight secondrow only .highlightling firstrow also because 'app' is there in role of firstrow..exact match should be highlight on every rows.please tell me.
Your code is behaving correctly. Just that you need to clear all previously highlighted rows on "keyup" of input text first.
if (text.length > 1) {
grid.find('tr:has(td)').css({ background: "" });
grid.find('tr').show();
......rest of your code.......
You need to clear the highlight before you parse. Add this statement of yours:
grid.find('tr:has(td)').css({ background: "" });
before entering this loop:
// iterate through all grid rows
grid.find('tr').each(function (i) {
...
});
Check this fiddle: http://jsfiddle.net/F3jRj/1/
And this updated fiddle with 3 columns: http://jsfiddle.net/F3jRj/2/

ASP.NET MVC 3 use C# code in cshtml file

I'm a little new to ASP.NET MVC3.
I have this code in a cshtml file
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
tableStyle: "grid",
headerStyle: "header",
rowStyle: "row",
footerStyle: "footer",
alternatingRowStyle: "altRow",
columns: grid.Columns(
grid.Column(header: "", format: #<text><input name="Checked" type="checkbox" value="#item.Key" /></text>, style: "CheckboxColumn", canSort: true),
grid.Column("Name", "Name"),
grid.Column("Address", "Address"),
grid.Column("City", "City"),
grid.Column("PhoneNumber", "Phone Number"),
grid.Column("", format: (item) =>
{
if (item.ID.Length > 0)
{
//CODE GOES HERE
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\" class=\"ToolTip\" title=\"ID # {1} <br> \" /></text>", Url.Content("~/images/coupled.png"), #item.ID.ToString()));
}
else
{
return Html.Raw("<text></text>");
}
}),
))
What I want is to write a C# Code at the //CODE GOES HERE section. in order to change the Url.Content("~/images/coupled.png")
epending on item ID.
So basically I want something like:
string URLOfPic;
if(item.ID > 1000)
{
URLOfPic="~/images/aaa.png
}
else
{
URLOfPic="~/images/bbb.png
}
and finally to use Url.Content(URLOfPic)
So how can I use that C# code in the page?
I hope I was clear.
Thank you very much for any help
PS: I want it to be a C# code and not a javascript or anything else.
In normal ASP.NET I can just use the code behind to do it. but in MVC3 I have no idea how
Being new to Asp.net mvc let me give you some advice, Don't Do That! The most code you should have in a view is a for loop, all of that kind of logic should be done in the action.
basically take your data and do all logic and formatting in the action and add it to a view model then pass that to the view. Other wise your going to create very brittle code blocks that won't error until run time
Modify your item class to add an image class. In the image class you can add Image.URL, Image.Title. This way in the controller you can assign the item an image based on it's ID. This will also allow you to more easily modify the image URLs at a single point of code, instead of modifying in every view that you use this logic in.
I think you are close, did this not work?
if (item.ID.Length > 0)
{
string URLOfPic;
if(item.ID > 1000)
{
URLOfPic="~/images/aaa.png";
} else {
URLOfPic="~/images/bbb.png";
}
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\" class=\"ToolTip\" title=\"ID # {1} <br> \" /></text>", Url.Content(URLOfPic), #item.ID.ToString()));
}

Categories