簡體   English   中英

無法在 ASP.NET 中顯示表單輸入

[英]Can't display form input in ASP.NET

我在 ASP.NET 4 中有簡單的視圖:

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

和簡單的 controller 應該在同一頁面上顯示來自表單的輸入:

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");
    }
}

提交后,我不斷收到我的"TBD"字符串。 我找不到任何關於它的東西,因為一切都基於我不需要的 model。

我建議使用強類型視圖而不是使用ViewBag 這將使您的代碼更清晰且易於維護。

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>

為什么不大量使用 ViewBag?

ViewBag 與 Model,在 MVC.NET 中

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM