Access different Controller Action from another View - asp.net-mvc

Say I have two different controllers i.e. Controller A and Controller B. How can I access Detail Action of Controller A from PartialView of Controller B.
I tried by javascript
document.location = '#Url.Action("Detail", "Controller A")' + "/#id=" + id; OR
windows.location = '#Url.Action("Detail", "Controller A")' + "/#id=" + id;
But its not working. is it a valid scenario?

The way you passing id if it is a action parameter is wrong, it should be like this -
document.location = "#Url.Action("Detail", "Controller A", new {id = "_Id"})".replace("_Id", id);

Related

set PageHeading in controller with m dash

I need to use &mdash (more beautiful as par my UI/UX designer), instead of regular '-' .
My question is how do I jam this html dash &mdash inside my controller where I am setting my pageHeading and BrowserTitle.
I am working with an MVC application, the code below is the controller which gets the result and then bundles up and sends it to the view.
In the View the PageHeading comes up automatically:
public ActionResult View()
{
var dto = _service.GetByID(id);
base.BrowserTitle = "Reports - " + report.ReportDisplayName;
base.PageHeading = "Reports - " + report.ReportDisplayName;
return View(dto);
}

Two ways of passing model back from view to controller

I'm new in MVC and have a question of principle about the way how the model is passed back from the view to the controller.
In the usual way the model-object comes from the controller, "spreads" its data into fields of the view and is then gone. The data will then be re-collected by a FormCollection-object passed back to the controller.
But there is also the other way where the model-object itself can be passed back to the controller as routedObject of e.g. an ActionLink, URL-Action or whatever. Then it's not necessary to spread and re-collect all the data.
In my work-place the other way is blocked, I get a warning about forbidden chars in the link-string. When investigating the issue I found that the other way seems mostly unknown.
For many reasons I think it's much better to pass the model-object back instead of the elaborate re-collecting of data.
So what is the reason for this curiosity please?
Update: Added View-Example
#model MvcApplication2.Models.TestClass
#{
#(Model.TestValue = 111);
}
<a href="#Url.Action("ValueBack", Model)">
<span>Test</span>
</a>
public void ValueBack(MvcApplication2.Models.TestClass testClass)
{
int x = testClass.TestValue;
}
In MVC we can get the values of the form in the controller by 3 ways.
Using the FormCollection Object.
Using the Parameters.
Strongly type model binding to view.
And I think it is not possible to send the model to the controller through the actionlink (as an ActionLink helper generates an anchor tag which when clicked sends a GET request to the server)
The Another Way :
Send the id of current model so that the controller action can fetch it back from the datastore from which it initially fetched it when rendering the View.
View:
#Ajax.ActionLink(
"Next",
"Step",
new {
StepId = 2,
id = Model.Id
},
new AjaxOptions { UpdateTargetId = "stepContainer" },
new { #class = "button" }
)
Controller:
public ActionResult Step(int StepId, int id)
{
var model = Repository.GetModel(id);
//Code
}

Capture the result of an Action by executing a Controller programatically (using RouteData)

I found the following answer from Darin Dimitrov - In ASP MVC3, how can execute a controller and action using a uri?
var routeData = new RouteData();
// controller and action are compulsory
routeData.Values["action"] = "index";
routeData.Values["controller"] = "foo";
// some additional route parameter
routeData.Values["foo"] = "bar";
IController fooController = new FooController();
var rc = new RequestContext(new HttpContextWrapper(HttpContext), routeData);
fooController.Execute(rc);
The only problem is that I like to capture the ViewResult that is returned by this Action (to render it as a string), but IController.Execute returns void.
I suspect I can find the Result somewhere in the property of the ControllerContext, but I can't find anything like that. Does anyone have an idea how to do this?
What you want to do, as far as I understand is to actually render the view, get the HTML result and assert against it.
This is practically testing the view which is pretty much not recommended and against most practices.
However, you could come up with some solutions to this. The one presented (simplified and a bit messy) is using RazorEngine to render the view. Since you can't get access to the .cshtml (the view file) from the test project you will need to get to its contents in a messy way.
Install RazorEngine NuGet package to your test project and try something along these lines:
[Fact]
public void Test()
{
var x = new HomeController(); // instantiate controller
var viewResult = (ViewResult)x.Index(); // run the action and obtain its ViewResult
var view = string.IsNullOrWhiteSpace(viewResult.ViewName) ? "Index" : viewResult.ViewName; // get the resulted view name; if it's null or empty it means it is the same name as the action
var controllerName = "Home"; // the controller name was known from the beginning
// actually navigate to the folder containing the views; in this case we're presuming the test project is a sibling to the MVC project, otherwise adjust the path to the view accordingly
var pathToView = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace("file:\\", "");
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.GetDirectoryName(pathToView);
pathToView = Path.Combine(pathToView, "WebApplication5\\Views\\" + controllerName + "\\" + view + ".cshtml");
var html = Razor.Parse(File.ReadAllText(pathToView), viewResult.Model); // this is the HTML result, assert against it (i.e. search for substrings etc.)
}

Route Links - Url.Action

I'm trying to return my links so they display as /Area_1419.aspx/2/1.
I've managed to get that result in example 2 but I don't understand why it works, as I would exspect example 1 below to work.
I don't see how Example 2 knows to go to the Area_1419 controller?
Route
routes.MapRoute(
"Area_1419 Section",
"Area_1419.aspx/{section_ID}/{course_ID}",
new { controller = "Home", action = "Index" }
);
Links Example 1
<a href='<%=Url.Action("Area_1419",
new { section_ID="2", course_ID="1" })%>'><img .../></a>
Returns: /Home.aspx/Area_1419?section_ID=2&course_ID=1
Links Example 2
<a href='<%=Url.Action("index",
new { section_ID="2", course_ID="1" })%>'><img .../></a>
Returns: /Area_1419.aspx/2/1
Remember - URLs are detached from your controllers and their actions.
That means - even bizzare URL such as "trolololo/nomnomnom/1/2/3" might and might not call Home/Index or any other controller/action combo.
In your case - example 2 actually does not know how to go to Area_1419 controller.
Url.Action figures out url from these route details:
"Area_1419.aspx/{section_ID}/{course_ID}"
But link still will call Home controller Index action because of default route values:
new { controller = "Home", action = "Index" }
Assuming that you got Area_1419 controller with Index action, your route should look like:
routes.MapRoute(
"Area_1419 Section",
"Area_1419.aspx/{section_ID}/{course_ID}",
new { controller = "Area_1419", action = "Index" } //changes here
);
This is what you are calling.
UrlHelper.Action Method (String, Object)
Generates a fully qualified URL to an action method by using the specified action name and route values.
This method overload does not try to figure out appropriate controller. It assumes that you know it (takes it out from current route values) and understands first string argument as an action name.
Try to use this one.
UrlHelper.Action Method (String, String, Object)
Generates a fully qualified URL to an action method by using the specified action name, controller name, and route values.
In your case:
Url.Action("Index","Area_1419", new { section_ID="2", course_ID="1" });
You can use Url.RouteUrl(), in your case
Url.RouteUrl("Area_1419 Section", new { controller = "Home", action = "Index", section_ID="2", course_ID="1"}
to be sure you use the correct route name, and get the correct URL no-matter-what.

Asp.net MVC Route Mapping

I have view names like Folder-One/Page-One.aspx I want to do a base controller implimentation that all request go to one Base Controller, that returns the view based on the context. Obviously still keeping the .aspx in the path
I have folders like getting-started/application-faq.aspx but what I want to do is I want to create 1 controller that does all the return views, as the pages are basicly static html
Is this possible?
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{view}.aspx", // URL with parameters
new { controller = "Base", action = "ChooseView" ,view ="Page-One"}
);
and your action can choose view to show :
publict ActionResult ChooseView (string viewName)
{
return View("~/Views/"+viewName);
}

Resources