나는 이것이 옳지 않다는 것을 알고 있지만, 설명을 위해 다음과 같은 것을하고 싶다 :
<%= Html.Button("Action", "Controller") %>
내 목표는 내 MVC 컨트롤러의 액션 메소드를 호출하는 HTML 버튼을 만드는 것입니다.
나는 이것이 옳지 않다는 것을 알고 있지만, 설명을 위해 다음과 같은 것을하고 싶다 :
<%= Html.Button("Action", "Controller") %>
내 목표는 내 MVC 컨트롤러의 액션 메소드를 호출하는 HTML 버튼을 만드는 것입니다.
답변:
조치를 게시하지 않으면 양식을 전혀 사용할 필요가 없습니다. 입력 버튼 (제출하지 않음)이 트릭을 수행합니다.
<input type="button"
value="Go Somewhere Else"
onclick="location.href='<%: Url.Action("Action", "Controller") %>'" />
public static string ActionButton(this HtmlHelper helper, string action, string controller, string text) { return String.Format("<input type=\"button\" value=\"{0}\" onclick=\"location.href='{1}' />",text,Url.Action(action,controller)); }
<input type="button" value="Go Somewhere Else" onclick="location.href='<%: Url.Action("Action", "Controller", new { parameter1 = value1 }) %>'" />
면도기 구문은 다음과 같습니다.
<input type="button" value="Create" onclick="location.href='@Url.Action("Create", "User")'" />
'input'
로 변경 'button'
하여 오류를 해결했습니다.
<button type="button" class="btn btn-primary" onclick="location.href='@Url.Action("action", "controller")'" >Go Somewhere Else</button>
하여 트릭을 수행
이 시도:
@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)
이것은 당신을 위해 작동합니다.
Url.Action을 사용하여 컨트롤러 조치에 대한 URL 생성을 지정할 수 있으므로 다음 중 하나를 사용할 수 있습니다.
<form method="post" action="<%: Url.Action("About", "Home") %>">
<input type="submit" value="Click me to go to /Home/About" />
</form>
또는:
<form action="#">
<input type="submit" onclick="parent.location='<%: Url.Action("About", "Home") %>';return false;" value="Click me to go to /Home/About" />
<input type="submit" onclick="parent.location='<%: Url.Action("Register", "Account") %>';return false;" value="Click me to go to /Account/Register" />
</form>
컨트롤러에서 작업을 구현할 때
return View("Index");
또는
return RedirectToAction("Index");
여기서 Index.cshtml (또는 작업을 생성하는 페이지) 페이지가 이미 정의되어 있습니다. 그렇지 않으면 "보기 또는 마스터를 찾을 수 없습니다 ..."오류가 발생했을 수 있습니다.
출처 : https://blogs.msdn.microsoft.com/aspnetue/2010/09/17/best-practices-for-asp-net-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")