문제

MVC 양식에 두 개의 버튼이 있습니다.

<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

내 컨트롤러 조치에서 어떤 압박을했는지 어떻게 알 수 있습니까?

도움이 되었습니까?

해결책

제출 버튼을 동일하게 지정하십시오

<input name="submit" type="submit" id="submit" value="Save" />
<input name="submit" type="submit" id="process" value="Process" />

그런 다음 컨트롤러에서 제출 가치를 얻으십시오. 클릭 한 버튼 만 값을 전달합니다.

public ActionResult Index(string submit)
{
    Response.Write(submit);
    return View();
}

물론 스위치 블록으로 다른 작업을 수행하기 위해 해당 값을 평가할 수 있습니다.

public ActionResult Index(string submit)
{
    switch (submit)
    {
        case "Save":
            // Do something
            break;
        case "Process":
            // Do something
            break;
        default:
            throw new Exception();
            break;
    }

    return View();
}

다른 팁

<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

컨트롤러 작업에서 :

public ActionResult SomeAction(string submit)
{
    if (!string.IsNullOrEmpty(submit))
    {
        // Save was pressed
    }
    else
    {
        // Process was pressed
    }
}

이것은 더 나은 답변이므로 버튼에 대한 텍스트와 값을 모두 가질 수 있습니다.

http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx

</p>
<button name="button" value="register">Register</button>
<button name="button" value="cancel">Cancel</button>
</p>

그리고 컨트롤러 :

public ActionResult Register(string button, string userName, string email, string password, string confirmPassword)
{
if (button == "cancel")
    return RedirectToAction("Index", "Home");
...

간단히 말해서 제출 버튼이지만 이름 속성을 사용하여 이름을 선택합니다. 컨트롤러 메소드 매개 변수의 이름 제출 또는 버튼에 대한 의무가 없기 때문에 더 강력합니다. 원하는대로 호출 할 수 있습니다 ...

아래와 같이 이름 태그에서 버튼을 식별 할 수 있습니다. 컨트롤러에서 이렇게 확인해야합니다.

if (Request.Form["submit"] != null)
{
//Write your code here
}
else if (Request.Form["process"] != null)
{
//Write your code here
}

다음은 사용자 정의 Multipttonattribute를 사용하여 지침을 따르기 쉬운 지침으로 수행하는 정말 멋지고 간단한 방법입니다.

http://blog.maartenballiauw.be/post/2009/11/26/supporting-multiple-submit-buttons-on-an-aspnet-mvc-view.aspx

요약하려면 다음과 같이 제출 버튼을 만드십시오.

<input type="submit" value="Cancel" name="action" />
<input type="submit" value="Create" name="action" /> 

다음과 같은 귀하의 행동 :

[HttpPost]
[MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
public ActionResult Cancel()
{
    return Content("Cancel clicked");
}

[HttpPost]
[MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
public ActionResult Create(Person person)
{
    return Content("Create clicked");
} 

이 수업을 만듭니다.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
    public string MatchFormKey { get; set; }
    public string MatchFormValue { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.Request[MatchFormKey] != null &&
            controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
    }
}
// Buttons
<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

// Controller
[HttpPost]
public ActionResult index(FormCollection collection)
{
    string submitType = "unknown";

    if(collection["submit"] != null)
    {
        submitType = "submit";
    }
    else if (collection["process"] != null)
    {
        submitType = "process";
    }

} // End of the index method

더 쉽게하려면 버튼을 다음과 같이 변경할 수 있다고 말할 것입니다.

<input name="btnSubmit" type="submit" value="Save" />
<input name="btnProcess" type="submit" value="Process" />

컨트롤러 :

public ActionResult Create(string btnSubmit, string btnProcess)
{
    if(btnSubmit != null)
       // do something for the Button btnSubmit
    else 
       // do something for the Button btnProcess
}

이 게시물은 오래 전에 응답을 받았기 때문에 Coppermill에 대한 대답하지 않을 것입니다. 내 게시물은 누가 이와 같은 해결책을 찾고자하는 사람에게 도움이 될 것입니다. 우선, "wduffy의 솔루션은 완전히 정확하다"고 말해야하며, 그것은 잘 작동하지만, 내 솔루션 (실제로 광산이 아님)은 다른 요소에 사용되며 컨트롤러가 컨트롤러와 더 독립적으로 만들어줍니다. 버튼의 레이블을 표시하는 데 사용되는 "value"는 다른 언어에 중요합니다.)

여기 내 해결책이 있습니다. 다른 이름을 알려줍니다.

<input type="submit" name="buttonSave" value="Save"/>
<input type="submit" name="buttonProcess" value="Process"/>
<input type="submit" name="buttonCancel" value="Cancel"/>

아래와 같은 동작의 인수로 버튼 이름을 지정해야합니다.

public ActionResult Register(string buttonSave, string buttonProcess, string buttonCancel)
{
    if (buttonSave!= null)
    {
        //save is pressed
    }
    if (buttonProcess!= null)
    {
        //Process is pressed
    }
    if (buttonCancel!= null)
    {
        //Cancel is pressed
    }
}

사용자가 버튼 중 하나를 사용하여 페이지를 제출하면 인수 중 하나만 가치가 있습니다. 나는 이것이 다른 사람들에게 도움이 될 것이라고 생각합니다.

업데이트

이 대답은 꽤 오래되었고 실제로 내 의견을 재고합니다. 어쩌면 위의 솔루션은 매개 변수를 모델의 속성에 전달하는 상황에 좋습니다. 자신을 귀찮게하지 말고 프로젝트를위한 최상의 솔루션을 취하십시오.

두 버튼 모두에 이름을 제시하고 양식에서 값을 확인하십시오.

<div>
   <input name="submitButton" type="submit" value="Register" />
</div>

<div>
   <input name="cancelButton" type="submit" value="Cancel" />
</div>

컨트롤러 측에서 :

public ActionResult Save(FormCollection form)
{
 if (this.httpContext.Request.Form["cancelButton"] !=null)
 {
   // return to the action;
 }

else if(this.httpContext.Request.Form["submitButton"] !=null)
 {
   // save the oprtation and retrun to the action;
 }
}

Core 2.2 Razor Pages 에서이 구문은 다음과 같습니다.

    <button type="submit" name="Submit">Save</button>
    <button type="submit" name="Cancel">Cancel</button>
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
        return Page();
    var sub = Request.Form["Submit"];
    var can = Request.Form["Cancel"];
    if (sub.Count > 0)
       {
       .......

request.form collection을 사용하여 찾을 수 없습니까? 프로세스가 요청을 클릭하면 request.form [ "process"]가 비어 있지 않습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top