Josh
Josh

Reputation: 13828

Multiple actions on the same controller and view in asp.net MVC

How do I use multiple actions on the same controller?

I'm using the default project that comes up when opening a new project in asp.net mvc.

I added one more Index action on the homecontroller to accept a value from a textbox...like this

 string strTest;
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection frm)
        {
            strTest = frm["testbox"];

            return RedirectToAction("Index");
        }

Now,I need to display the entered value back to the user. How do I do this?

I tried this..

public ActionResult Index()
{
    this.ViewData.Add("ReturnMessage", strValue);
    return View();
}

Here's what I've put on my view..

<% using (Html.BeginForm())
   { %>
<p>
    <%=Html.TextBox("testbox")%>
</p>
<p>
    <input type="submit" value="Index" /></p>
<p>
    <%= Html.ViewData["ReturnMessage"] %>
</p>
<% } %>

the compiler typically doesn't let me add another index with same constructor to display the entered message back to the user which is obvious in c# I know. But,then how do I get the message back out to the user. Thanks

Upvotes: 1

Views: 3086

Answers (3)

griegs
griegs

Reputation: 22770

Simple method

In your view

<% using (Html.BeginForm()) {%>
    <%= Html.TextBox("myInput") %>
    <%= ViewData["response"] %>
<%}%>

In your controller;

public ActionResult Index()
{
  return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection collection)
{
  ViewDate.Add("response", collection["myInput"]);
  return View();
}

Upvotes: 1

griegs
griegs

Reputation: 22770

Josh, see the previous question you asked.

In there I had <%= Html.textbox("myInput", Model.myInput....

it's the Model.myInput that will put the value from your model into the text of yoru text box.

EDIT

Or if you don't want it in a text box then simply do;

EDIT 2

You can add as many items into your new form view model and it has, in this case, nothing to do with a database. see your previous question on where i declared the class.

the class can have as many properties as you like. So you can add a string myResponse {get;set;} to return a response back to your view so then you can use <%=Model.myResponse%>

Hope this helps.

Upvotes: 1

Zachary Scott
Zachary Scott

Reputation: 21198

Well, a controller matches one route, based on the parameters sent. You can layer your routes from most specific to least specific, it checks in order. First one that hits wins.

The other answer is to either strongly type your model sent to your view, or store it in the ViewData:

ViewData["Message"] = "Welcome to ASP.NET MVC!";

Then access it in your View:

<%= Html.Encode(ViewData["Message"]) %>

Upvotes: 3

Related Questions