Change view in MVC - c#

I am new to MVC.
I need to have two views (for same logic) one for normal browser and one for mobile.
How I can I redirect to different view for Mobile?
right now i have two controller but i want to use only one controller (HomeController.cs) for both views.
I know this way, I should have my mobile views under "Home".
Please help me to redirect to Mobile view using only one controller.
i am using below for redirect for now (with two controllers):
return RedirectToAction("Index", "Mobile");
I am using framework 3.5 and MVC 2

I'm having a little trouble picturing your setup. My guess is you have the current setup:
Controllers
- HomeController.cs
- MobileController.cs
Views
- Home
--Index.aspx
- Mobile
--Index.aspx
But you want:
Controllers
- HomeController.cs
Views
- Home
--Index.aspx
- Mobile
--Index.aspx
Is that correct?
Update:
Aas people mentioned below it's one of those 'that's just how MVC works' sort of deal. 'Home' is a location you can go to, but 'Mobile' is a specific type of page. If you add another area called "About" as new Views subfolder, where would you put your mobile folder? What is mobile now supposed to handle? If mobile is not supposed to replicate the regular site, then it should have its own controller, even if it replicates some code (don't forget you can create classes outside the controllers that can do the brunt of the work that any controller can call).
On the other hand if you want a mobile version of each of your pages you should be adding them under the views folder for each route. For example:
Controllers
- HomeController.cs
Views
- Home
- Mobile
-- Index.aspx
--Index.aspx
I'm not exactly sure where you are doing the logic to figure out if they are on a mobile platform, but assuming for now it's in the controller somewhere in your HomeController.cs you then have:
public ActionResult Index() {
if([check for mobile])
{
return View("Mobile/Index");
} else {
return View("Index");
}

Add a Mobile View Engine.

Home Controller
create To Action like
Public ActionResult Index()
{
}
And Another Action (Mobile)
Public ActionResult Mobile()
{
}
Single Controller Have Many Action(View)
Controllers
- HomeController.cs
Views
- Home
--Index.chtml
- Mobile
--Index.chtml

Related

ASP.NET MVC Razor cannot find views in area

URLs work correctly
Actions work correctly
the only problem is that the razor engine is just searching for view files in ~/Views and not in ~/Areas/Admin and I don't know why is that because it used to work fine
It works when I fill the return view type of the action by the exact path of its view but the absolute path for views is not working
Here is one action for example but none of the actions in the admin area can call their views
Even _Logout which is a partial view ib Shared cannot be called by _Layout unless using the full path
Action in Controller:
// GET: Admin/Login
[Route("Admin/Login")]
public ActionResult Login()
{
return View();
}
Error:
The view 'Login' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Default/Login.aspx
~/Views/Default/Login.ascx
~/Views/Shared/Login.aspx
~/Views/Shared/Login.ascx
~/Views/Default/Login.cshtml
~/Views/Default/Login.vbhtml
~/Views/Shared/Login.cshtml
~/Views/Shared/Login.vbhtml
Solved!
[RouteArea("Admin", AreaPrefix = "")]
Was missing from top of my controller

ASP.NET MVC view cannot find asset

I'm making an ASP.NET MVC website. Most of my views are under the View and their respective subfolders, and they are called Index. These views have no trouble fetching CSS and Images. These classes have localhost:51227/example like URLs.
However, when I add a view that is just another ActionResponse of a controller, the view cannot find any of my assets (images, css etc.). These views have localhost:51227/example/action.
What am I doing wrong with my routing?
Sample code:
public ActionResult Day()
{
ClientViewModel cvm = new ClientViewModel();
cvm.Page = Page.TIMESHEET;
return View(cvm);
}
This is my Controller ActionResult.
The thing was that my inner URL's didn't start with a / so I wasn't looking from root.
Stupid question, sorry.

How to add View routing in a .net core project?

I have created a .Net Core Web API program. I want to add a single view to it. Under the same project I add a "Views" folder. In the HomeController, where I am routing all my API requests, I created the following:
[HttpGet("view")]
public IActionResult Index()
{
return View();
}
In my Views folder I created a folder "Home" and added "Index.cshtml" to it.
When I launch the API, and navigate to "../view" I get to the return View(); line, but then it returns a 500 Internal Server Error.
This is what I don't like about the "automagical" approach of MVC convention. I have no idea where to link a view to a controller if the convention didn't work.
Update, this probably should have been my first course of action.
I added a new class to Controllers folder, and used the MVC Controller template in VS2015. I then added a view to match, and it still doesn't work automagically.
So for clarity, my project is: ASP.NET Core Web Application(.NET Core) with a Web API template. I have a "Jobs" controller class that was added at the start as 'Values' and I renamed. Then I added an MVC Controller Class named "HomeController" with the only method being "Index". I added a folder named "Views" and a subfolder named "Home", and added an MVC View Page named "Index.cshtml".
I tried to use "return View();" in the Index method, didn't work. I then tried to add [Route("Home/Index")] above the Index method. Either way, the URL will get me to my break point at "return View();" but it will never return the view.
Note : It's a little strange that you want to return a view in a Web API project, a Web API project is supposed to return some data structure, like json using return new JsonResult(your_json_here) for example.
Note 2 : you need the Microsoft.AspNetCore.Mvc framework (which is installed with the Web API template)
Anyway, you have different ways to configure routing in a asp.net core application :
Creating and extending default routes
Example of routing configuration in the Configure method :
app.UseMvc(routes =>
{
// You can add all the routes you need here
// And the default route :
routes.MapRoute(
name: "default_route",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" }
);
});
Using attributes
If you configure routing with attributes, don't forget the controller's one :
Example for the route /index :
[Route("")]
public class HomeController : Controller
{
[HttpGet]
[Route("[action]")]
public IActionResult Index()
{
return View();
}
}
Example for the route /home/index :
[Route("[controller]")]
public class HomeController : Controller
{
[HttpGet]
[Route("[action]")]
public IActionResult Index()
{
return View();
}
}
Example for the route /iputwhatiwant/actionnameiwant :
[Route("iputwhatiwant")]
public class HomeController : Controller
{
[HttpGet]
[Route("actionnameiwant")]
public IActionResult Index()
{
return View();
}
}
My screen of a .NET Core Web API project returning a view :
For more information, the official documentation is well-documented : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing
How are you running this webapp, from the Windows commandline?... can you give us the detailed HTTP500 error. It will probably reveal something different than routing errors because that usually gives 404.
[Route("[controller]")]
public class HomeController : Controller
Note the automagical "[controller]" in the Route definition, I think its necessary now
It took me a frustratingly long while to learn the routing convention as it was being developed, but it seems to have normalized out for a few versions. Check out this tutorial documentation on the subject in MVC: Attribute Routing in ASP.NET MVC 5, which is MVC not WebCoreAPI where it is likely based from. If you have a better documentation specific to Web Core API, use that.
This ASP.NET Web Core Build a web API tutorial documentation has some good points about what you seem to be trying to do. Specifically, the section title "Getting to-do items" has this code:
[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(long id)
{
var item = _todoRepository.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
Looking at that with benefit of some measure of MVC routing experience, it looks particularly different from your approach in that the HTTP verb annotation member property value used is a query parameter.
Seeing I am guessing using known inexpertise, still, I think you need to get the attribute routing fixed, and maybe return an ObjectResult instead of a view, as NightOwl888 suggests. The server error might also have much more useful information along with the exception message.
EDIT: Sorry, I may have misunderstood your question. If you are trying to build an app that serves dynamic web pages instead of a WebAPI that serves data object results, this Build an MVC Web App tutorial, similar to the "Build a web API" tutorial I mentioned before might have your app structure problem answer. If you are trying to do both, you should probably start with the MVC Web App structure or use two separate projects.
The (only) way I have got this working is to declare the path as an attribute on the action - in the same way you have done but with the format as below (Controller/Action):
[HttpGet("Home/Index")]
public IActionResult Index()
{
return View();
}
I was missing:
"preserveCompilationContext": true
in the build options of my project.json

Add a view and display it?

I'm totally new to MVC. Now I'm trying to create a View in the folder Sample( which is under the folder of Views). I right-clicked the Sample folder and selected "Add View", then hit the view name as Test. After the view has been created, I typed in following code:
<!DOCTYPE html>
<html>
<head>
<title>Sample View</title>
</head>
<body>
<p>
Test
</p>
</body>
</html>
Build. Then I tried to navigated the address http://localhost:24694/Sample/Test in my browser. But the browser read "The resource cannot be found.". Why? I've also other cshtml files in the Sample folder(which was generated by others), they worked fine. For example, there is a file called "Message.cshtml" under the folder of Sample, and I can navigate the address http://localhost:24694/Sample/Message with ease. Is there anything that I should add?
3 Step Process
1 - Define the Route
routes.MapRoute("Test", "test",
new { controller = "NameOfController", <- In your case TestController
action = "Index", <- Name of action in controller returning view
parameter = "parameterName - leave empty if no params needed"
});
2 - Create the controller
So if you follow the above method and call your route Test and the view Test then you need to create the controller called TestController. MVC automagically sows these together thanks to your route config you did earlier (RouteConfig.cs)
3 - View
In your case you just make sure the view is returning something.
Easy as that. Good luck.
you cannot use
http://localhost:24694/Sample/Test
to navigate to view because you can only access a view through a controller. so follow these steps
First of all create a new controller inside controllers folder and name it 'SamplController'.
By default there will be an action method named Index().
Create a new Action method named 'Test' inside 'SampleController'
Now right click inside 'Test' action method and click on Add View. it will add a new view insides Views folder named 'Test.cshtml'. You can use it. if you want to place this View inside other folder then you've to modify the return statement of 'Test' action method. For example you created a folder 'MyViews' inside Views folder and moved 'Test.cshtml' there. Now your return statement in 'Test' action method will be like this
return View("~Views/Sample/MyViews/Test.cshtml");
instead of
return View();
Now when you use
http://localhost:port/Sample/Test
it will create a new instance of 'Sample' Controller and will call 'Test' action method. This method will return specified view. i hope it will help :)
ASP.NET MVC is based on routing not in file system like asp.net webforms. Following the internals, views should be in the Views folder from the ASP.NET MVC application template, like Controllers should stay on the Controllers folder. It is not required, but it is setted by default from asp.net mvc framework.
In your a Controller (class), you could have some Actions (methods), which can return a view, image, file, etc, implementations that derive from ActionResult type. Theses actions, could return a view using the View method from the controller base class. By default, the asp.net mvc will search for a view (.cshtml or .aspx file) inside the ´Views` folder and in a folder with the same name of the Controller, for sample, if you have a controller like this:
public class ProductController : Controller
{
public ActionResult Index()
{
return View();
}
}
It will find a view in Views/Product/Index.cshtml and render it for you. I recommend you reading more in http://asp.net/mvc

How can I use asp.net MVC Areas to setup an application to serve my different clients using same code base

I am seeking help in setup an application so that I can give my clients their own url for browsing.
I am thinking about creating asp.net MVC application and by using AREAS feature ( I will consider each area as my client) I will develop individual application for my client and provide them the url which will serve a their own application running.
Basically, I want to keep my all clients in one application but give them different url.
As areas works as follows:
localhost:5699 -- it will land to default home controller and index page
ocalhost:5699/area1/home/index - it lands to Home controller or Area and renders index view of this area
and so on for another area.
So. I want to ask, can i use this approach to give my clients unique url which I can map to particular Area of application and client can browse simple typing their url and that land to index page of that area?
for example:
www.area1.com -- I want to map this url to localhost/5699/area1/home/index.aspx
www.area2.com -- I want to map this url to localhost/5699/area2/home/index.aspx
Please help, how can i will setup all above in production and development environment
Basically, i want to setup my application such that if my client want different UI and additional functionality I can easily alter respective controller.
If I understand the question correctly, I think you can accomplish your goal by way of the Route and RoutePrefix attributes. These attributes will decorate controllers and methods and give you the ability to tweak the URL's exactly how you want it.
localhost/5699/area1/home/index
[RoutePrefix("area1")]
public class Area1Controller: ApiController
{
[Route("home/index")]
public ActionResult Index()
{
// controller logic here
}
}
localhost/5699/area2/home/index
[RoutePrefix("area2")]
public class Area2Controller: ApiController
{
[Route("home/index")]
public ActionResult Index()
{
// controller logic here
}
}

Categories

Resources