Search code examples
c#asp.net-corerazordevextreme

How do I use an asp-action in a Asp.Net Core DevExtreme DataGrid column in a Razor page?


I have an Asp.NetCore web app built using EFC written in C#. The webpages are built using Razor. I am attempting to use a DevExpress DevExtreme DataGrid in a page.

Here is my model class definition:

public class Owner
{
    [Key]
    public Guid OwnerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
}

Here is my page definition:

@model IEnumerable<Owner>
@{ Layout = "_DevExtremeLayout"; ViewBag.Title = "All Owners";}

@(Html.DevExtreme().DataGrid<SmartTracPoc.Models.Owner>()
    .DataSource(Model)
    .RemoteOperations(true)
    .Columns(columns => {
        columns.AddFor(m => m.FirstName);
        columns.AddFor(m => m.LastName);
        columns.AddFor(m => m.PhoneNumber);
        columns.AddFor(m => m.OwnerId).CellTemplate(@<text><form asp-action="DeleteOwner" method="post">
                    <input type="hidden" value="m => m.OwnerId" name="OwnerId" />
                    <input type="image" src="/icon/close.png" />
                </form>
                </text>);       
    })
)

Here is the associated code snippet from the controller file:

public class OwnerController : Controller
{
    [HttpPost]
    public async Task<IActionResult> DeleteOwner(Guid ownerId)
    {
        try
        {
            var requestString = SmartTrocPocServerAddress + $"Owners/{ownerId.ToString()}";
            var response = await client.DeleteAsync(requestString);
            var responseString = await response.Content.ReadAsStringAsync();
        }
        catch (HttpRequestException ex)
        {
            Debug.WriteLine("OwnerController::DeleteOwner() - exception occured");
            Debug.WriteLine(ex.Message);
        }

        return RedirectToAction("Index");
    }
}

I'd like to use an asp-action in a column definition to fire the associated Delete method in my controller. The DeleteOwner() method in the controller is successfully getting fired, but my id parameter is 0.

Previous to using the DevExtreme DataGrid, the following page definition snippet worked correctly:

@foreach (var r in Model)
{
 <table>
  <tbody>
   <tr>
    <td>
     <form asp-action="DeleteOwner" method="post">
        <input type="hidden" value="@r.OwnerId" name="OwnerId" />
        <input type="image" src="/icon/close.png" />
     </form>
    </td>
   </tr>
  </tbody>
 </table>
}

How do I bind the OwnerId to the on the call to my controller method call?


Solution

  • Try this:

    <input type="hidden" value="<%- data.OwnerId %>" name="OwnerId" />