0

我的 MVC4 项目中有自定义 HTML Helper 方法,此方法返回 WebGrid 的 html url,如下所示:

<img title="Delete" src="../../Content/delete.png">

我将此图像用作 GridView 上 Actions 列的按钮。另一方面,当我单击删除按钮时,由于 id 字段隐藏在相关实体模型中并且无法传递给控制器​​,因此出现问题。因为当我使用下面的代码在同一个视图中进行测试时,它可以工作并且相关记录被删除:

@Html.ActionLink("Delete", "Delete","Admin", new { studentId = 10} )
   @Html.Hidden("StudentID", 10)
                <input type="submit" value="Delete" />

}

因此,很明显问题与隐藏场有关。你能澄清一下如何解决这个问题吗?我想继续使用我的 HTML Helper,以便我可以在 GridView 的同一列上使用多个图像按钮,如下所示:

....
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()
 )
)
....

这是我定义的 HTML Helper 类:

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);
}


控制器:

[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");
}
4

1 回答 1

0

我建议您使用按钮的图像简单地创建一个 CSS 类:

.edit-button {
    display: block;
    height:24px; //size of your img
    width:24px;
    background: url('myImage.jpg');
}

在您看来,您只需创建一个 ActionLink 并指定要使用的类:

@Html.ActionLink(" ", "Detail", "Admin", new { id = 10}, new { @class = "edit-button" })

然后在你的 Controller 中完成:

public ActionResult Edit(int id)
{
    //do something
    return View();
}

如果认为这是使用图像创建 ActionLink 的更好选择。

希望能帮助到你 !

于 2013-11-05T13:13:42.977 回答