Reputation:
Consider my route setting:
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+" }
);
}
What I want is:
1) If a url like myserver/123
, then call Home.ViewQuestion(string number)
.
2) Otherwise, search in controllers and actions, with Home/Index
default action
What I am getting now when requesting myserver/123
is:
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
My Action and View:
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>
Upvotes: 1
Views: 1092
Reputation: 1294
From your controller's action, it's seems like you are returning the view name as the number passed to it. So MVC runtime is looking for 123.html or 123.aspx while you have defined your view as ViewQuestion.cshtml.
public ActionResult ViewQuestion(int? number)
{
return View(number + "");
}
You need to return the correct view name as following
public ActionResult ViewQuestion(int? number)
{
return View("ViewQuestion",number);
}
Upvotes: 1
Reputation:
Turned out that I was calling controller helper method View(string viewName)
, as if it is View(object model)
!!!
public ActionResult ViewQuestion(string questionNumber)
{
return View((object)questionNumber);
}
Upvotes: 0
Reputation: 990
Instead of url: "{number}" , use url: "ViewQuestion/{number}" and your action code:
public ActionResult ViewQuestion(int? number)
{
//your code
}
Upvotes: 1