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.

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
Erwol
  • 15
  • 8
  • You are not setting ViewBag.City in the action that handles POST. When you debug GetWeather is `city` correct based on the form input? – Crowcoder Jun 03 '21 at 14:11
  • @Crowcoder yes, while debugging, cityName sets to string passed in argument, after redirecting to Index, it is "TBD" again – Erwol Jun 04 '21 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. – Crowcoder Jun 04 '21 at 15:38
  • Thank you, I thought it is instantiated per session – Erwol Jun 05 '21 at 15:56

2 Answers2

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 MVC.NET

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
0

try this

[HttpPost]
 public ActionResult GetWeather(string city)
{
    cityName = city;
    return Index();
}
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
Serge
  • 40,935
  • 4
  • 18
  • 45