且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.Net MVC 如何将数据从视图传递到控制器

更新时间:2023-02-25 19:36:26

您可以使用 ViewModel 来实现,就像您将数据从控制器传递到视图一样.

You can do it with ViewModels like how you passed data from your controller to view.

假设你有一个这样的视图模型

Assume you have a viewmodel like this

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

在您的 GET 操作中,

and in your GET Action,

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

并且您的视图必须强类型为 ReportViewModel

and your view must be strongly typed to ReportViewModel

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

以及控制器中的 HttpPost 操作方法

and in your HttpPost action method in your controller

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

OR 简单地说,您可以在没有 POCO 类(视图模型)的情况下做到这一点

OR Simply, you can do this without the POCO classes (Viewmodels)

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

并且在您的 HttpPost 操作中,使用与文本框名称同名的参数.

and in your HttpPost action, use a parameter with same name as the textbox name.

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

根据评论

如果你想发布到另一个控制器,你可以使用这个BeginForm 方法的重载.

If you want to post to another controller, you may use this overload of the BeginForm method.

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

从动作方法传递数据到视图?

您可以使用相同的视图模型,只需在 GET 操作方法中设置属性值

Passing data from action method to view ?

You can use the same view model, simply set the property values in your GET action method

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" />
}