I have custom HTML Helper method in my MVC4 project and this method returns an html url for WebGrid as below:
<img title="Delete" src="../../Content/delete.png">
I use this image as a button for the Actions column on my GridView. On the other hand when I click Delete button, there is a problem due to the id field is hidden in the related Entity model and cannot be passed to the controller. Because when I use the code below for testing in the same view it works and the related record is deleted:
@Html.ActionLink("Delete", "Delete","Admin", new { studentId = 10} )
@Html.Hidden("StudentID", 10)
<input type="submit" value="Delete" />
}
So, it is clear that the problem is related to hidden field. Could you please clarify about how to solve this problem? I want to continue to use my HTML Helper so that I can use multiple image button on the same column in my GridView like below:
....
grid.Column("Actions", format: (item) =>
new HtmlString(
@Html.ActionImage("../../Content/detail.png", "Detail", "my-class", "Detail", "Admin", new { item.StudentID}).ToString() +
@Html.ActionImage("../../icons/edit.png", "Edit", "my-class", "Edit", "Admin", new { item.StudentID}).ToString() +
@Html.ActionImage("../../icons/delete.png", "Delete", "my-class", "Delete", "Admin", new { item.StudentID}).ToString()
)
)
....
And here is the HTML Helper class I defined:
public static MvcHtmlString ActionImage(this HtmlHelper html, string imagePath, string alt, string cssClass,
string action, string controllerName, object routeValues)
{
var currentUrl = new UrlHelper(html.ViewContext.RequestContext);
var imgTagBuilder = new TagBuilder("img"); // build the <img> tag
imgTagBuilder.MergeAttribute("src", currentUrl.Content(imagePath));
imgTagBuilder.MergeAttribute("title", alt);
imgTagBuilder.MergeAttribute("class", cssClass);
string imgHtml = imgTagBuilder.ToString(TagRenderMode.SelfClosing);
var anchorTagBuilder = new TagBuilder("a"); // build the <a> tag
anchorTagBuilder.MergeAttribute("href", currentUrl.Action(action, controllerName, routeValues));
anchorTagBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorTagBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
Controller:
[HttpPost]
public ActionResult Delete(int studentId)
{
Student deletedStudent = repository.DeleteStudent(studentId );
if (deletedStudent != null)
{
TempData["message"] = string.Format("{0} was deleted",
deletedStudent.Name);
}
return RedirectToAction("Index");
}
I propose you to simply create a CSS class with the image of your button :
In your view, you just have to create an ActionLink and specify the class to use :
And then to finish, in your Controller :
If think this is the better choice to create an ActionLink with an image.
Hope it helps !