ASP.NET MVC:如何将Post请求结果返回至视图并展示?
解决方案
方法一:使用ViewBag传递数据
修改Post请求的控制器方法,将结果存入ViewBag后返回视图:
public ActionResult Test() { return View(); } [HttpPost] public ActionResult Test() { Service1Client o = new Service1Client(); bool result = o.Test(); // 返回布尔值True System.Diagnostics.Debug.WriteLine(result); // 输出True // 将结果存入ViewBag ViewBag.Result = result; return View(); }
在.cshtml视图中读取ViewBag的值:
<p>@ViewBag.Result</p>
如果后续需要传递字符串结果,直接把ViewBag.Result赋值为字符串即可,视图写法无需改动。
方法二:使用强类型ViewModel(推荐)
创建ViewModel类封装要传递到视图的数据:
public class TestViewModel { public bool Result { get; set; } // 后续需要传递字符串时,可添加对应属性 // public string StringResult { get; set; } }
修改控制器方法,实例化ViewModel并赋值后返回:
public ActionResult Test() { return View(); } [HttpPost] public ActionResult Test() { Service1Client o = new Service1Client(); bool result = o.Test(); System.Diagnostics.Debug.WriteLine(result); var viewModel = new TestViewModel { Result = result // 若为字符串结果,赋值对应属性 // StringResult = "你的字符串内容" }; return View(viewModel); }
修改视图,指定强类型模型:
@model TestViewModel <p>@Model.Result</p> <!-- 若有字符串属性,可这样显示:<p>@Model.StringResult</p> -->
你之前ViewBag无效的原因
你之前的代码没有在Post方法中给ViewBag赋值,视图自然无法获取数据。ViewBag在当前请求周期内有效,Post请求返回视图属于同一请求周期,只要正确赋值就能在视图中读取。
内容的提问来源于stack exchange,提问作者Jessica
相关产品推荐
相关产品推荐

