考虑我的路线设置:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Question",
url: "{number}",
defaults: new { controller = "Home", action = "ViewQuestion" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { id = "\\d+" }
);
}
我想要的是:
1)如果网址为myserver/123
,请拨打Home.ViewQuestion(string number)
。
2)否则,使用Home/Index
默认操作
我在申请myserver/123
时获得的是:
The view '123' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/123.aspx
~/Views/Home/123.ascx
~/Views/Shared/123.aspx
~/Views/Shared/123.ascx
~/Views/Home/123.cshtml
~/Views/Home/123.vbhtml
~/Views/Shared/123.cshtml
~/Views/Shared/123.vbhtml
我的行动和观点:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AdvancedWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ViewQuestion(int? number)
{
return View(number + "");
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
ViewQuestion.cshtml:
@model string
@{
ViewBag.Title = "ViewQuestion";
}
<h2>ViewQuestion: @Model</h2>
答案 0 :(得分:1)
而不是网址:“{number}”,请使用网址:“ViewQuestion / {number}”和您的操作代码:
public ActionResult ViewQuestion(int? number)
{
//your code
}
答案 1 :(得分:1)
从您的控制器的操作中,您似乎将视图名称作为传递给它的号码返回。因此,当您将视图定义为ViewQuestion.cshtml时,MVC运行时正在寻找 123.html 或 123.aspx 。
public ActionResult ViewQuestion(int? number)
{
return View(number + "");
}
您需要返回正确的视图名称,如下所示
public ActionResult ViewQuestion(int? number)
{
return View("ViewQuestion",number);
}
答案 2 :(得分:0)
原来我正在调用控制器辅助方法View(string viewName)
,好像它是View(object model)
!!!
public ActionResult ViewQuestion(string questionNumber)
{
return View((object)questionNumber);
}