MVC 动作只返回 viewbag 结果
MVC action returning just viewbag result
我是 MVC 5 的新手。
我在 MyController 目录中有一个名为 MyPage.cshtml 的页面。在该页面上,我有一个 link 定义为....
@Html.ActionLink("Get Info", "GetInfo", "MyController", new { myId = 1 }, null)
因此,在 MyController 控制器中我有一个 GetInfo 方法。我只是想让它做一些事情,填写 ViewBag 结果,然后 return 返回到它所在的同一页面,即 MyPage。但是在加载页面时出现 'Object reference not set to an instance of an object.' 错误。我正在考虑重定向到 MyPage 它的模型丢失了。这是我的代码....
public ActionResult GetInfo(int myId){
// do stuff
ViewBag.Result = "this is a test";
return this.View("MyPage");
}
所以,为简化起见:我实际上只处理一个页面,MyPage。 link 点击只是调用一个自定义方法来做一些事情,我希望它 return 回到原来的位置。请问有什么建议吗?
您遇到此错误
Object reference not set to an instance of an object.
因为您的视图 MyPage
取决于您未发送的模型。
有多种方法可以处理您的第二个问题:
如果您想在执行 GetInfo
操作后显示我的页面,您将要使用 TempData[""]
:
public ActionResult GetInfo(int myId)
{
// do stuff
TempData["Result"] = "this is a test";
return RedirectToAction("MyPage");
}
然后在您的 MyPage
视图中:
@TempData["Result"]
另一个(不太理想的)选项是填充 MyPage 的模型,return 它就像您最初所做的那样,这不会执行“重定向”:
public ActionResult GetInfo(int myId){
// do stuff
ViewBag.Result = "this is a test";
var model = // ... populate model like (or from) MyPage
return View("MyPage", model);
}
我是 MVC 5 的新手。
我在 MyController 目录中有一个名为 MyPage.cshtml 的页面。在该页面上,我有一个 link 定义为....
@Html.ActionLink("Get Info", "GetInfo", "MyController", new { myId = 1 }, null)
因此,在 MyController 控制器中我有一个 GetInfo 方法。我只是想让它做一些事情,填写 ViewBag 结果,然后 return 返回到它所在的同一页面,即 MyPage。但是在加载页面时出现 'Object reference not set to an instance of an object.' 错误。我正在考虑重定向到 MyPage 它的模型丢失了。这是我的代码....
public ActionResult GetInfo(int myId){
// do stuff
ViewBag.Result = "this is a test";
return this.View("MyPage");
}
所以,为简化起见:我实际上只处理一个页面,MyPage。 link 点击只是调用一个自定义方法来做一些事情,我希望它 return 回到原来的位置。请问有什么建议吗?
您遇到此错误
Object reference not set to an instance of an object.
因为您的视图 MyPage
取决于您未发送的模型。
有多种方法可以处理您的第二个问题:
如果您想在执行 GetInfo
操作后显示我的页面,您将要使用 TempData[""]
:
public ActionResult GetInfo(int myId)
{
// do stuff
TempData["Result"] = "this is a test";
return RedirectToAction("MyPage");
}
然后在您的 MyPage
视图中:
@TempData["Result"]
另一个(不太理想的)选项是填充 MyPage 的模型,return 它就像您最初所做的那样,这不会执行“重定向”:
public ActionResult GetInfo(int myId){
// do stuff
ViewBag.Result = "this is a test";
var model = // ... populate model like (or from) MyPage
return View("MyPage", model);
}