我知道这是不对的,但为了说明问题,我想这样做:
<%= Html.Button("Action", "Controller") %>
我的目标是使一个HTML按钮,将调用我的MVC控制器的动作方法。
我知道这是不对的,但为了说明问题,我想这样做:
<%= Html.Button("Action", "Controller") %>
我的目标是使一个HTML按钮,将调用我的MVC控制器的动作方法。
当前回答
你总是可以使用htmlHelpers来构建一些东西
public static IHtmlContent BtnWithAction(this IHtmlHelper htmlHelper, string id, string text, string css="", string action="", string controller="")
{
try
{
string str = $"<button id=\"{id}\" class=\"{css}\" type=\"button\" ###>{text}</button>";
if (!string.IsNullOrEmpty(action) && !string.IsNullOrEmpty(controller))
{
string url = ((TagBuilder)htmlHelper.ActionLink("dummy", action, controller)).Attributes["href"];
var click = !string.IsNullOrEmpty(url) ? $"onclick=\"location.href='{url}'\"" : string.Empty;
return new HtmlString(str.Replace("###", click));
}
return new HtmlString(str.Replace("###", string.Empty));
}
catch (Exception ex)
{
Log.Error(ex, ex.Message);
var fkup = "<script>alert(\"assumption is the mother of all failures\")</script>";
return new HtmlString(fkup);
}
}
然后在视图中这样调用它
@Html.BtnWithAction("btnCaretakerBack", "Back", "btn btn-primary float-right", "Index", "Caretakers")
其他回答
最好用这个例子。
使用ActionLink调用动作和控制器:
@Html.ActionLink("Submit", "Action", "Controller", route, new { @class = "btn btn-block"})
<button type="button" onclick="location.href='@Url.Action("MyAction", "MyController")'" />
Type ="button"阻止页面提交,而是执行您的操作。
举个例子:
<button name="nameButton" id="idButton" title="your title" class="btn btn-secondary" onclick="location.href='@Url.Action( "Index","Controller" new { id = Item.id })';return false;">valueButton</button>
如果你在主页(“/ home /Index”),你想调用管理控制器的索引动作,下面将为你工作。
<li><a href="/Admin/Index">Admin</a></li>
你总是可以使用htmlHelpers来构建一些东西
public static IHtmlContent BtnWithAction(this IHtmlHelper htmlHelper, string id, string text, string css="", string action="", string controller="")
{
try
{
string str = $"<button id=\"{id}\" class=\"{css}\" type=\"button\" ###>{text}</button>";
if (!string.IsNullOrEmpty(action) && !string.IsNullOrEmpty(controller))
{
string url = ((TagBuilder)htmlHelper.ActionLink("dummy", action, controller)).Attributes["href"];
var click = !string.IsNullOrEmpty(url) ? $"onclick=\"location.href='{url}'\"" : string.Empty;
return new HtmlString(str.Replace("###", click));
}
return new HtmlString(str.Replace("###", string.Empty));
}
catch (Exception ex)
{
Log.Error(ex, ex.Message);
var fkup = "<script>alert(\"assumption is the mother of all failures\")</script>";
return new HtmlString(fkup);
}
}
然后在视图中这样调用它
@Html.BtnWithAction("btnCaretakerBack", "Back", "btn btn-primary float-right", "Index", "Caretakers")