Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

publicclassMyController : 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>

Solution 2:

If you are using asp.net mvc, then please follow mvc pattern like this ..

View

@using (@Html.BeginForm("Search","Home",FormMethod.Post))
{
 <b>Name : </b>@Html.TextBox("searchTerm", null, new { @id = "txtSearch" })
 <input type="submit" value="Search" />
}

Controller

[HttpPost]
    public ActionResult Search(string searchTerm)
    {
        return View(searchTerm);
    }
}

Solution 3:

Search.cshtml

<formaction="/Home/Search"method="get"><inputtype="text"name="q" /><inputtype="submit"value="Search" /></form><pclass='current-query'>@Model</p>

HomeController.cs

public ActionResult Search(string q)
{
    return View((object)q); // return the model to the view (a string)
}

Post a Comment for "How Do I Send Data To Asp.net Controller So That It Can Return A View?"