Reputation: 25
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.
Upvotes: 0
Views: 176
Reputation: 8985
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
Upvotes: 1
Reputation: 43969
try this
[HttpPost]
public ActionResult GetWeather(string city)
{
cityName = city;
return Index();
}
Upvotes: 0