ASP.Net MVC如何从视图数据传递给控制器 [英] ASP.Net MVC How to pass data from view to controller
问题描述
我是完全新的ASP.Net,我相信这是一个非常基本的问题
我有一个观点,其中有一个环节生成的报告,但要能够产生报告中,我必须向用户提供一个合适的文字名称,以及。
I am completely new to ASP.Net and I am sure this is a very basic question I have a View in which there is a link to generate report but to be able to generate report I must ask the user to provide a suitable text name as well.
到目前为止,我已经能够通过从服务器的数据使用从我的控制器,查看传递模型查看,但我不知道如何从视图数据传递到我的控制器。
So far I have been able to pass data from server to view using Models passed from my controller to view, but I am not sure how to Pass data from view to my controller.
我只需要从视图中传递一个字符串到控制器,在这种情况下。
I just need to pass a string from view to controller in this case.
例如用任何意见将AP preciated。
Any advice with example will be appreciated.
更新
我明白我必须把数据上传回服务器,但如何做在razorhtml code和控制器的形式REALIZE?
I understand I have to post the data back to server but how does that realize in the form of razorhtml code and controller ?
谢谢,
推荐答案
您可以用怎么样,你从你的控制器通过查看数据的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" />
}
这篇关于ASP.Net MVC如何从视图数据传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!