如何将数据发送到asp.net控制器以便它可以返回视图? [英] How do i send data to asp.net controller so that it can return a view?

查看:89
本文介绍了如何将数据发送到asp.net控制器以便它可以返回视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是如此简单,我仍然在尝试使用c#和MVC应用程序来学习ASP.NET,但是我只是遇到了一个很简单的例子,然后我可以从它,它是怎么回事:我有一个简单的html5表单,方法是GET,类型是文本,我基本上想要提交一个文本到我的mvc控制器,一旦我的控制器得到它,我希望它输出该字符串'工作'通过HTML5,我该怎么做?

What I want to do is so simple, I'm still trying to learn ASP.NET with c# and MVC application but I'm just having a lot of difficulty getting a simple example to go through, then I can grow from it, here's how it goes: I have a simple html5 form that's method is GET, the type is text and I basically want to submit a text into my mvc controller, once my controller get's it, I want it to output that string 'worked' through HTML5, how do I do this?

摘要:字符串'working' - > html表单 - > c#c​​ontroller - > html(view?)

summary: string 'worked' --> html form --> c# controller --> html (view?)

这是我的'view'所得到的(Search.cshtml)

here's what I got for my 'view' (Search.cshtml)

<form action="Home/Search" method="get">
<input type="text" name="q" />
<input type="submit" value="Search" />

好的,到目前为止一切顺利,如果我输入'working',除非我添加更多代码,否则不会发生任何事情,这里是c#(HomeController.cs):

ok, so far so good, if I input 'worked' nothing is going to happen unless I add more code, here's c# (HomeController.cs):

 public ActionResult Search(string q)
    {

        return this.View(q?); // so what exactly is View(q)? what is view returning?        }

好吧这就是我困惑的地方,我的字符串经过并存入'q ?如果是这样,我如何使用HTML5输出类似

okay so this is where I am confused, does my string go through and become stored in 'q'? and if so, how do I get this thing to use HTML5 to output something like

<p> q </p> <!-- q = 'worked' -->


推荐答案

在您的控制器中,您正在调用查看(...)方法不正确。 View(...)方法要求您传递的字符串参数是您尝试渲染的剃刀视图的路径。

In your controller, you are calling the View(...) method incorrectly. The View(...) method expects the string parameter you're passing to be the path to the razor view you're trying to render.

q 变量从控制器传递到要渲染的视图的快速而简单的方法是使用 ViewBag

A quick and simple way to pass the q variable from your controller to a view to be rendered is using ViewBag.

如果你有一个名为 /Views/Search.cshtml 的剃须刀视图,你会这样做:

If you have a razor view named /Views/Search.cshtml you would do:

public class MyController : Controller
{
  public ActionResult Search(string q)
  {
    ViewBag.Query = q;
    return View("~/Views/Search.cshtml");
  }
}

然后在 /Views/Search.cshtml 像这样使用:

<p>@ViewBag.Query</p>

这篇关于如何将数据发送到asp.net控制器以便它可以返回视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆