且构网

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

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

更新时间:2023-02-25 19:23:49

您可以用怎么样,你从你的控制器通过查看数据的ViewModels做到这一点。

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;}
}

和在你付诸行动,

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
}

简单地说,你可以这样做没有POCO类(的ViewModels)

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