求MVC关于Views调用control方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication2.Controllers
{
public class DefaultController : Controller
{
//
// GET: /Default/
public ActionResult Index()
{
return View();
}
public HtmlString GetStr()
{
string str = "<p>21312</p>";
return new HtmlString(str);
}
}
}
@using MvcApplication2.Controllers
@model DefaultController
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Model.GetStr()
错误提示
未将对象引用设置到对象的实例。
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。
源错误:
行 9: <h2>Index</h2>
行 10:
行 11: @Model.GetStr()
[解决办法]
试试看
return View();
=>
return View(new DefaultController());
也许可以
不过,这真是一种好奇葩的写法。
[解决办法]
@{Html.RenderAction("动作名", "控制器名");}[解决办法]
@{Html.RenderAction("GetStr", "Default");}