0

I have simple view in ASP.NET 4:

<form action="GetWeather" method="post">
    <input name="city" type="text" />
    <input type="submit" />
</form>
<h1>@ViewBag.City</h1>

And simple controller which was supposed to display input from the form on the same page:

public class WeatherController : Controller
{
    string cityName = "TBD";
    public ActionResult Index()
    {
        ViewBag.City = cityName;
        return View();
    }

    [HttpPost]
    public ActionResult GetWeather(string city)
    {
        cityName = city;
        return Redirect("/Weather/Index");
    }
}

After submit I keep getting my "TBD" string. I couldn't find anything about it, as everything is based on model, which I don't need.

4
  • You are not setting ViewBag.City in the action that handles POST. When you debug GetWeather is city correct based on the form input? Commented Jun 3, 2021 at 14:11
  • @Crowcoder yes, while debugging, cityName sets to string passed in argument, after redirecting to Index, it is "TBD" again Commented Jun 4, 2021 at 15:20
  • That is because every request instantiates a new WeatherController and you are setting it to "TBD". I encourage you to pass viewmodels to views instead of relying on viewbag. Commented Jun 4, 2021 at 15:38
  • Thank you, I thought it is instantiated per session Commented Jun 5, 2021 at 15:56

2 Answers 2

1

I would recommend to use strongly typed view instead of using the ViewBag. It would make your code cleaner and easy to maintain.

public class WeatherController : Controller
{
    public ActionResult Index(string city = "TBD")
    {
        return View((object)city);
    }

    [HttpPost]
    public ActionResult GetWeather(string city)
    {            
        return RedirectToAction("Index", new { city });
    }
}
@model string

@using (Html.BeginForm("GetWeather", "Weather", FormMethod.Post))
{
    <input name="city" type="text" />
    <input type="submit" />
}

<h1>@Model</h1>

Why not to use ViewBag heavily?

ViewBag vs Model, in ASP.NET MVC

Sign up to request clarification or add additional context in comments.

Comments

0

try this

[HttpPost]
 public ActionResult GetWeather(string city)
{
    cityName = city;
    return Index();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.