FluffyWuffy FluffyWuffy - 3 months ago 8
ASP.NET (C#) Question

How do i send data to asp.net controller so that it can return a view?

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?

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

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




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


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' -->

Answer

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.

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

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

Then in /Views/Search.cshtml use it like this:

<p>@ViewBag.Query</p>
Comments