it-source

ASP.Net MVC 보기에서 컨트롤러로 데이터를 전달하는 방법

criticalcode 2023. 6. 10. 09:27
반응형

ASP.Net MVC 보기에서 컨트롤러로 데이터를 전달하는 방법

저는 ASP.Net을 완전히 처음 접하며 이것이 매우 기본적인 질문이라고 확신합니다. 보고서를 생성하는 링크가 있지만 보고서를 생성할 수 있으려면 사용자에게 적절한 텍스트 이름을 제공하도록 요청해야 합니다.

지금까지 컨트롤러에서 보기로 전달된 모델을 사용하여 서버에서 보기로 데이터를 전달할 수 있었지만 보기에서 컨트롤러로 데이터를 전달하는 방법을 잘 모르겠습니다.

이 경우에는 뷰에서 컨트롤러로 문자열을 전달하기만 하면 됩니다.

예를 들어 조언을 해주시면 감사하겠습니다.

갱신하다

서버에 데이터를 다시 게시해야 하는 것은 이해하지만, 어떻게 그것이 레이저 html 코드와 컨트롤러의 형태로 실현됩니까?

컨트롤러에서 보기로 데이터를 전달하는 방법과 같은 View Model을 사용하여 이 작업을 수행할 수 있습니다.

다음과 같은 뷰 모델이 있다고 가정합니다.

public class ReportViewModel
{
   public string Name { set;get;}
}

그리고 당신의 GET Action에서,

public ActionResult Report()
{
  return View(new ReportViewModel());
}

그리고 당신의 견해는 강하게 타이핑되어야 합니다.ReportViewModel

@model ReportViewModel
@using(Html.BeginForm())
{
  Report NAme : @Html.TextBoxFor(s=>s.Name)
  <input type="submit" value="Generate report" />
}

컨트롤러의 HttpPost 작업 방법에서

[HttpPost]
public ActionResult Report(ReportViewModel model)
{
  //check for model.Name property value now
  //to do : Return something
}

또는 POCO 클래스 없이도 이 작업을 수행할 수 있습니다(모델 보기).

@using(Html.BeginForm())
{
   <input type="text" name="reportName" />
   <input type="submit" />
}

및 HttpPost 작업에서 텍스트 상자 이름과 동일한 이름의 매개 변수를 사용합니다.

[HttpPost]
public ActionResult Report(string reportName)
{
  //check for reportName parameter value now
  //to do : Return something
}

편집: 코멘트대로

다른 컨트롤러에 게시하려는 경우 BeginForm 메서드의 오버로드를 사용할 수 있습니다.

@using(Html.BeginForm("Report","SomeOtherControllerName"))
{
   <input type="text" name="reportName" />
   <input type="submit" />
}

작업 방법에서 보기로 데이터 전달?

동일한 뷰 모델을 사용할 수 있습니다. GET 작업 방법에서 속성 값을 설정하기만 하면 됩니다.

public ActionResult Report()
{
  var vm = new ReportViewModel();
  vm.Name="SuperManReport";
  return View(vm);
}

그리고 당신이 보기에

@model ReportViewModel
<h2>@Model.Name</h2>
<p>Can have input field with value set in action method</p>
@using(Html.BeginForm())
{
  @Html.TextBoxFor(s=>s.Name)
  <input type="submit" />
}

게시를 원하지 않거나 게시해야 하는 경우:

@Html.ActionLink("link caption", "actionName", new { Model.Page })  // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);

[HttpGet]
public ActionResult actionName(int reportID)
{

보고서에 유의하십시오.새 {} 요소의 ID가 일치 보고서와 일치합니다.작업 매개 변수의 ID는 이 방법으로 임의의 수의 매개 변수를 추가할 수 있지만, 2개 또는 3개 이상의 매개 변수(일부는 항상 논쟁)는 POST를 통해 모델을 전달해야 합니다(다른 답변에 따라).

편집: 주석에서 지적한 대로 올바른 오버로드에 대한 null이 추가되었습니다.여러 가지 오버로드가 있으며 action+controller를 모두 지정할 경우 routeValues와 htmlAttributes가 모두 필요합니다.컨트롤러(캡션+액션만)가 없으면 routeValues만 필요하지만 둘 다 항상 지정하는 것이 가장 좋습니다.

<form action="myController/myAction" method="POST">
 <input type="text" name="valueINeed" />
 <input type="submit" value="View Report" />
</form> 

컨트롤러:

[HttpPost]
public ActionResult myAction(string valueINeed)
{
   //....
}

언급URL : https://stackoverflow.com/questions/20333021/asp-net-mvc-how-to-pass-data-from-view-to-controller

반응형