【问题标题】:Can't display form input in ASP.NET无法在 ASP.NET 中显示表单输入
【发布时间】:2021-06-03 14:03:37
【问题描述】:

我在 ASP.NET 4 中有简单的视图:

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

还有一个简单的控制器,它应该在同一页面上显示来自表单的输入:

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" 字符串。我找不到任何关于它的东西,因为一切都是基于模型的,我不需要。

【问题讨论】:

  • 您没有在处理 POST 的操作中设置 ViewBag.City。当您根据表单输入调试 GetWeather 时 city 是否正确?
  • @Crowcoder 是的,在调试时,cityName 设置为传入参数的字符串,重定向到 Index 后,它又是“TBD”
  • 这是因为每个请求都会实例化一个新的 WeatherController 并且您将其设置为“TBD”。我鼓励你将视图模型传递给视图,而不是依赖于 viewbag。
  • 谢谢,我以为它是每个会话实例化的

标签: c# .net asp.net-mvc


【解决方案1】:

我建议使用强类型视图而不是使用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>

Why not to use ViewBag heavily?

ViewBag vs Model, in MVC.NET

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      相关资源
      最近更新 更多