简体   繁体   中英

Can't display form input in ASP.NET

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.

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

try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM