In .NET MVC, I see it always follows this naming convention: RouteName in the controller and it is a view called 'RouteName.cshtml'.
My question is how can I use SAME cshtml file with different RouteName?
The default View() method defaults to matching the Action name, but you can use the View(string) method to specify that path to your desired CSHTML, like in the following example:
// in action method that is *not* RouteName
return View("RouteName");
You can re-use chunks of CSHTML with partials; depending on the problem that you're trying to solve, this may be a better solution.
Can you edit your question and add more context? Why do you need to render the same cshtml from more than one ActionResult method? What are you trying to accomplish?
For example, you have a view named About.cshtml
You have 2 action methods and both of them are using About.cshtml
So you can try
public ActionResult Index()
{
var model = "view model";
// Pass view model as the second parameter
return View("About", model);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
// Not need pass view name because view name and action method name are same (About
return View();
}
Related
Im a fresher using .NET
I have 1 view and then I create a new controller..
can I use that existing view to display the data from my new controller ?
Yes, just pass that View to your controller:
return View("View", ModelHere);
If your View or CSHTML file is Record.cshtml, you can pass it like:
return View("Record", ModelHere)
or
return View("Record");
If its on different folder and still under View Folder:
return View("../FolderName/Record");
Yes you can. You can have several controllers using the same view. All you have to do is to mention the name of your view in the return statement of the controller.
return View("ViewName");
I'm new on asp.net mvc. I created a basic controller and I tried to open it using url. But rendering is not finished and my controller didn't display in several minutes. I did not change anything from default asp.net 5 mvc project also my controller's index method return only hello world string. I don't is there any problem on iis or VS. Any idea about that problem?
Thanks for help.
In MVC only public methods that return an ActionResult are accessible as web pages.
So you MUST use something like this:
public class HelloWorldController : Controller
{
// GET: HelloWorld/Index
public ActionResult Index()
{
return Content("This is <b>Index</b> action...");
}
// etc
}
Content(...) is a special method the wraps text into an ActionResult.
Note: only use Content(...) if you specifically do NOT want to use a View such as Index.cshtml - which is what you normally WOULD do, of course.
I've got a controller named "TafelController.cs" and a view named "Berekenen.cshtml". (the names aren't made up by me.)
the url "http://localhost:5181/tafel/berekenen" somehow doesn't work, even when adding extensions to berekenen like ".cshtml".
Decapitalizing the names of the controller and the view also doesn't work.
The thing is, I get the proper view when I make the Index() method the following.
public ActionResult Index()
{
return View("berekenen");
}
which is weird, because that's what
http://localhost:portnum/tafel/berekenen
is.
when setting that page as the startpage the URL differs a bit.
Then it becomes
http://localhost:5181/Views/tafel/berekenen.cshtml
Does anyone have any idea what might be happening?
http://localhost:portnum/tafel/berekenen is trying to navigate to a method named Berekenen on TafelController. You need to add the following method
public ActionResult Berekenen()
{
return View();
}
I have opened a sample ASP.NET MVC project.
In HomeController I have created a method (action) named MethodA
public ActionResult MethodA()
{
return View();
}
I have right clicked on MethodA and created a new view called MethodA1
Re-did it and created a new view called MethodA2.
How is this magical relationship done? I looked for the config to tell the compiler that views MethodAX are related to action MethodA, but found none.
What view will the controller return when MethodA is called?
The convention is that if you don't specify a view name, the corresponding view will be the name of the action. So:
public ActionResult MethodA()
{
return View();
}
will render ~/Views/ControllerName/MethodA.cshtml.
But you could also specify a view name:
public ActionResult MethodA()
{
return View("FooBar");
}
and now the ~/Views/ControllerName/FooBar.cshtml view will be rendered.
Or you could even specify a fully qualified view name which is not inside the views folder of the current controller:
public ActionResult MethodA()
{
return View("~/Views/Foo/Baz.cshtml");
}
Now obviously all this assumes Razor as view engine. If you are using WebForms, replace .cshtml with .aspx or .ascx (if you are working with partials).
For example if there is no view it will even tell you where and in what order is looking for views:
Remember: ASP.NET MVC is all about convention over configuration.
The MVC framework use convention over configuration. The framework calls the ExecuteResult on the ViewResult object (created by the return View();). The framework by convention then looks in a number of locations to find a view
If you are using areas the framework will look in the following locations for a view.
/Areas//Views/ControllerName/ViewName.aspx
/Areas//Views/ControllerName/ViewName.ascx
/Areas//Views/Shared/ViewName.aspx
/Areas//Views/Shared/ViewName.ascx
/Areas//Views/ControllerName/ViewName.cshtml
/Areas//Views/ControllerName/ViewName.vbhtml
/Areas//Views/Shared/ViewName.cshtml
/Areas//Views/Shared/ViewName.vbhtml
Without areas (or if you are using areas and no view has been found) the framework will look at the following locations
/Views/ControllerName/ViewName.aspx
/Views/ControllerName/ViewName.ascx
/Views/Shared/ViewName.aspx
/Views/Shared/ViewName.ascx
/Views/ControllerName/ViewName.cshtml
/Views/ControllerName/ViewName.vbhtml
/Views/Shared/ViewName.cshtml
/Views/Shared/ViewName.vbhtml
As soon as the Framework tests a location and finds a file, then the search stops,
and the view that has been found is used to render the response to the client.
There are a number of overriden versions of the View method. The most common one is to render a specific view, outside of the framework convention, by calling it by name. For example
return View("~/Views/AnotherIndex.cshtml");
As an interesting footnote, the framework looks for legacy ASP, C# and VB Razor views (aspx, ascx, cshtml and vbhtml) even though you have a specific view engine.
In MVC controller action is not bound to view.
It uses delegate mechanism to pickup the view.
Model Binding(Mapping)
I was looking for the same and I just made a couple of tests and figured out.
It doesn't save anywhere.
To understand how it works; just do these steps:
In your controller, right click, Add View
Then enter a different View Name
and Ctrl F5
you will get Server error in application.
For example if you right click , Add View in following Index action method and type "Index2" in View name, you will get the error.
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
}
}
So basically there is a 1-1 matching between action name and View name. And you cannot add view for the same method so there is no need to save in a config file.
Now change the view file name in Visual Studio from Index2.cshtml to Index.cshtml then Ctrl+F5. You should see it is working.
I am trying to build a functionality where I need to a create a candidate's profile in our application. There are two steps/UI's to create a candidate's profile:
1 - Create template...where the user enters candidate's information.
2 - Preview template...where the user will be shown a preview of how their profile would look like once they add the profile to our system.
I have already created the views to support these UI's via a controller called "CandidateController" which contains few action methods:
1- [HttpGet] "Create" that returns a Create template.
[HttpGet]
public ViewResult Create()
2- [HttpPost] "Preview" that returns a Preview template.
[HttpPost]
public ActionResult Preview(ProfileViewModel viewModel)
Now what I need to implement is to have a button/link in the Create template that would call the action method [HttpPost] Preview in the controller.
Challenge
I am also wondering if there is a way that the model binder would load the ViewModel object for me if am able to call the HttpPost Preview action method from the first create template.
I am looking for a suggestion/help to how to best achieve this kind a functionality.
Any help will be deeply appreciated.
Challenge I am also wondering if there is a way that the model binder
would load the ViewModel object for me if am able to call the HttpPost
Preview action method from the first create template.
You could use either a standard form or an AJAX call to invoke the Preview POST action and pass all the property values of the view model then. All the values you pass in this request will be the values that will be bound by the default model binder. Here's an article explaining how the default model binder expects the parameters to be named for more complex structure such as lists and dictionaries.
Example with AJAX:
$.ajax({
url: '#Url.Action("Preview")',
type: 'POST',
data: { Prop1: 'value 1', Prop2: 'value 2' },
success: function(result) {
// TODO: do something with the result returned from the POST action
}
});
If you don't want to use AJAX you could use a standard form with hidden fields:
#using (Html.BeginForm())
{
#Html.Hidden("Prop1", "value 1")
#Html.Hidden("Prop2", "value 2")
...
<button type="submit">Preview</button>
}
OK so here are the options that I had to get around:
As Darin suggested you may go with the unobtrusive way by using $.ajax(options), however the thing is you might want to go this way only if you want to do a partial page update or if you want to work on updating/dumping new html in the same view.
And if you don't want to use the Ajax, instead of using Hidden fields, you can simply use the TempData property in MVC, this is how I implemented my targeted functionality using TempData. p.s.below...
[HttpPost]
public ActionResult Create(ViewModel viewModel)
{
this.TempData["profile"] = viewModel;
return RedirectToAction("Preview");
}
public ActionResult Preview()
{
if (TempData["profile"] != null)
{
return View((ViewModel)TempData["profile"]);
}
// Handle invalid request...
return null;
}
So, this solution worked pretty well for me, where I did not write any JavaScript or unnecessary HTML. AND thanks Darin for directing me to a starting point.