제출 버튼을 누른 MVC
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" />
그런 다음 컨트롤러에서 submit 값을 가져옵니다.클릭한 단추만 값을 전달합니다.
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
}
}
이것이 더 나은 답변이므로 버튼에 대한 텍스트와 값을 모두 가질 수 있습니다.
</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
}
다음은 사용자 지정 MultiButton 특성을 사용하여 지시사항을 매우 쉽게 따를 수 있는 정말 멋지고 간단한 방법입니다.
요약하자면, 제출 단추를 다음과 같이 만드십시오.
<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
}
이 게시물은 코퍼밀이 오래 전에 답변을 받았기 때문에 그에게 답변을 하지 않을 것입니다.제 글은 누가 이런 해결책을 찾는지에 도움이 될 것입니다.먼저, "WDuffy의 솔루션은 완전히 정확합니다."라고 말해야 합니다. 그리고 잘 작동합니다. 하지만 제 솔루션(실제로는 제 솔루션이 아닙니다)은 다른 요소에서 사용될 것이고 프레젠테이션 계층을 컨트롤러로부터 더 독립적으로 만듭니다(컨트롤러는 버튼의 레이블을 표시하는 데 사용되는 "값"에 의존하기 때문입니다).이 기능은 다른 언어에 중요합니다.)
다음은 제 솔루션입니다. 다른 이름을 지정하십시오.
<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
}
}
사용자가 단추 중 하나를 사용하여 페이지를 제출하면 인수 중 하나만 값을 가집니다.저는 이것이 다른 사람들에게 도움이 될 것이라고 생각합니다.
갱신하다
이 대답은 꽤 오래된 것이고 저는 실제로 제 의견을 재고합니다. 아마도 위의 해결책은 모델의 속성에 매개 변수를 전달하는 상황에 좋습니다.번거롭게 하지 말고 프로젝트에 가장 적합한 솔루션을 선택하십시오.
Request를 사용하여 찾을 수 없습니까?양식 모음?프로세스를 클릭한 경우 요청을 클릭합니다.양식["process"]은(는) 비워 둘 수 없습니다.
두 단추에 이름을 지정하고 양식에서 값을 확인합니다.
<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 페이지에서는 이 구문이 작동합니다.
<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)
{
.......
언급URL : https://stackoverflow.com/questions/1714028/mvc-which-submit-button-has-been-pressed
'IT' 카테고리의 다른 글
| WPF에서 메뉴 모음을 생성하시겠습니까? (0) | 2023.04.28 |
|---|---|
| 각도:경로를 변경하지 않고 queryParams를 업데이트하는 방법 (0) | 2023.04.28 |
| 백슬래시로 셸 명령을 시작하는 이유는 무엇입니까? (0) | 2023.04.28 |
| Ubuntu 13.10으로 업그레이드한 후 Eclipse 메뉴가 표시되지 않음 (0) | 2023.04.28 |
| "테이블을 다시 만들어야 하는 변경 내용 저장 방지" 부정적 영향 (0) | 2023.04.28 |