我知道这是不对的,但为了说明问题,我想这样做:
<%= Html.Button("Action", "Controller") %>
我的目标是使一个HTML按钮,将调用我的MVC控制器的动作方法。
我知道这是不对的,但为了说明问题,我想这样做:
<%= Html.Button("Action", "Controller") %>
我的目标是使一个HTML按钮,将调用我的MVC控制器的动作方法。
当前回答
举个例子:
<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>
其他回答
好的,你基本上需要将动作传递给按钮,并在点击发生时调用它,它不需要在from中,你可以使用HTML onclick on button在按钮被点击时触发它…
<button id="my-button" onclick="location.href='@Url.Action("YourActionName", "YourControllerName")'">Submit</button>
最好用这个例子
<a href=“@Url.Action(”Register“,”Account“, new {id=Item.id })” class=“btn btn-primary btn-lg”>Register</a>
在控制器中实现动作时,使用
return View("Index");
or
return RedirectToAction("Index");
在索引。CSHTML(或生成动作的页面)页面已经定义。否则,您可能会遇到“视图或其主未找到…”错误。
来源:https://blogs.msdn.microsoft.com/aspnetue/2010/09/17/best-practices-for-asp-net-mvc/
尽管使用onclick方法,你也可以像下面这样使用formaction:
<button type="submit" id="button1" name="button1" formaction='@Url.Action("Action", "Controller")'>Save</button>
你总是可以使用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")