问题
I could not find any solution for my problem. This is a MVC project I am working on.
In the GridView how can I do this: Click on row and then click on button to delete this selected or clicked row.
Don't need any solution with automatic Select button.
So
Mouse click on the row
get its Id or any value
Button that redirect to my function + Id.
Is it impossible with gridview? would it be better if I use Table?
This is what I have tried:
//To get the id
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.RowIndex.ToString();
string id = DataBinder.Eval(e.Row.DataItem, "Id").ToString();
e.Row.Attributes.Add("rowid", id);
}
}
My javascript an button
<a href='<%=ResolveUrl("~/Producter/Delete?id=" ) %>' ID="HyperLink1">Delete</a>
<script type ="text/javascript" language="javascript">
//every time a row is clicked this script will perform the following actions:
$("tr").click(function () {
var clicked = $(this);
//get the row id from the currently cliked row
var rowid = clicked.attr("rowid");
//get the value of href attribute from the link with id 'HyperLink1'
var link = $("#HyperLink1").attr("href");
//remove any previously appended values
var linkTokens = link.split("=");
linkTokens[1] = "";
link = linkTokens.join("=");
//append the current row id to the link
link = link + rowid;
//set the href attribute of your link to the new value
$("#HyperLink1").attr("href", link);
});
</script>
Got id = undefined all the time.
回答1:
If you're using MVC, I think you got the usage of GridView all wrong as I can see from your code behind. This is a server control which isn't compatible with MVC since it depends on PostBack and ViewState. You can do it quite easily in "MVC oriented fashion":
Let's say you want to show list of Products from an action method called 'Products'.
- Right-Click that controller action and add new View.
- A modal dialog pops up.
- Name that view 'Products'.
- Choose from the list the type it will strongly bound to, hence 'Product' class.
- Choose the type of view as 'List'.
- Choose the layout page (Like MasterPage in ASP.NET).
- that's it.
Now, in the controller action, you shold call that View and pass it a collection of Products, something like that:
public ActionResult Products()
{
List<Products> products = SomeMethodToGetProducts();
return View(products);
}
Simple!
All you have to do now is populate the actions in the generated view like 'Edit', 'Delete' and so on.
来源:https://stackoverflow.com/questions/16495896/whats-the-best-way-for-select-row-delete-it-on-button-click