Search code examples
c#.netasp.net-mvc-4webgridactionlink

WebGrid ActionLink how to get row object


I have WebGrid which is build using Model I build it using code below:

View

@model IEnumerable<ExampleMVC4.Models.LicenseInfo>
@{
    ViewBag.Title = "Licenses";
    WebGrid grid = new WebGrid(Model);    
}
<h2>Licenses</h2>
@grid.GetHtml(tableStyle: "table table-striped table-hover",
  columns: new[] {
    grid.Column("SerialNumber"),                                   
    grid.Column("Name"),
    grid.Column("Organization"),
    grid.Column("Email"),
    grid.Column("DateActivated"),
    grid.Column(header: "IsValid", format: item=>new HtmlString(Html.ActionLink((string)item.IsValid.ToString(), "Deactivate", new { @id =  item.SerialNumber} ).ToString()))
  })
  <p>@ViewBag.Message</p>

Control

public ActionResult Index()
{
    var data = getLicenseInfoList();
    return View(data);
}

[HttpPost]
public ActionResult Deactivate(string serialNum_)
{
    if (serialNum_ != null)
    {
        ViewBag.Message = serialNum_;
    }
    return View();
}

But I am unable to get it to call Deactivate() function with serial number.

What is the proper way to handle ActionLink click inside WebGrid?


Solution

  • Your ActionLink is generating a route parameter named id ( ... new { @id = item.SerialNumber} .. but you methods parameter name is serialNum_. Change the methods signature to

    [HttpGet]
    public ActionResult Deactivate(string id)
    

    Note also its a link so its a GET, not a POST (although its not clear what the method does)