I want to embed a link to a controller action in my page so I can use it from javascript. Something like
var pollAction = '/Mycontroller/CheckStatus'
Now I am happy to hardcode it, but it would be really nice if there were a method I could use to create the URL. The AjaxHelper/HtmlExtensions contain methods to create hyperlinks (.ActionLink(...) and so on), but if you look into the guts of them, they rely on a method called UrlHelper.GenerateUrl() to resolve a controller and action into a url. This is internal so I can't really get at this.
Anyone found a good method in the framework to do this? Or must I roll my own?
Have you tried something along these lines?
var pollAction = '<%=Url.Action("CheckStatus", "MyController") %>';
If your page or control inherits from ViewPage or ViewUserControl, use the Url.Action method.
If not, use this instead:
String url = RouteTable.Routes.GetVirtualPath
(
((MvcHandler) HttpContext.Current.CurrentHandler).RequestContext,
new RouteValueDictionary
(
new
{
controller = "MyController",
action = "CheckState",
id = idParameter
}
)
).VirtualPath;
Place this inside a method on your code-behind and call it from the HTML view.
Related
I want to decide where to send each url at runtime.
I don't want to use attributes like [Route("/hello")] and I don't want to use the conventional [controller=hello]/[action=Index]. What I want is a way to execute a specific controller after deciding with my own logic like this
if(context.Request.Path.Value == "/hello"){
SomehowCallTheActionOnController("MyController", "MyAction", anyUrlValuesLikeId);
}
Using the DynamicRouteValueTransformer, I can get the dictionary of values such as values["controller"]="home"; But since I want to catch all, in my case I only get "values["all"]="hello/this/is/my/url", even if I set the controller name manually, it won't work because I don't want to use the conventional mapping of controllers and actions.
I guess what I'm trying to do is the equivalent of Route::get('/user', [UserController::class, 'index']); in laravel for example; use my own routing but let asp pass dependency injections to controllers and instantiate ActionContext for me. Is this possible at all in ASP.NET?
I can just use
app.MapGet("myroute", async context => {
var actionContext = new ActionContext(context, context.getRouteData(), new ActionRequest());
await new ContentResult(){ Content = "hi" }.ExecuteResultAsync(actionContext);
})
and manage dependency injections on my own by GetService... but I'm not sure this is how it's supposed to be done because the actionRequest for example won't have all necessary properties set up, and asp might be using it for something??
Anyway, thanks in advance :)
I found the issue. When you specify the controller name for the route, you must not include the word "Controller"!
Like this:
app.MapControllerRoute(
"About",
"/About/{something}",
defaults: new { controller = "App", action = "Index" }
);
and the controller name is "AppController" with a method "Index" like this
public class AppController : Controller {
public IActionResult Index(string something) {
return /* put your result here */;
}
}
I still don't know how to specify a method (GET, POST, etc) with "MapControllerRoute" but at least this way I can specify routes from an array with templates and names...
I have a controller where there are two action methods with same name with HttpPost and HttpGet as shown below , when link with #Url.Action("DoSomething","Controller") is called then both the method are invoked , how do I call only GET method?
Is there anyway to pass type GET or POST in #URL.Action or any other way?
[HttpGet]
public ActionResult DoSomething(int ? MyParam)
{
}
[HttpPost]
public ActionResult DoSomething(MyModel Model)
{
}
In Razor View When I build a link like
JustDoIt
Then it calls both POST and GET methods, even after specifiying parameter as int and not the model
Try adding post in the form declaration:
#using (Html.BeginForm("DoSomething","Controller", FormMethod.Post))
{
}
or using HTML:
<form action="#Url.Action("DoSomething","Controller")" method="POST">
...
</form>
The HTTP verb POST/GET will route your request to the appropriate action. The default is GET.
I think that you maybe getting Url.Action() confused with Html.Action() (apologies if I'm wrong). As someone mentioned in the comments, Url.Action() will just render a URL based on the parameters which is intended for say building anchor tags. Html.Action() on the other hand will invoke an action when building the page for the response at server side which I'm guessing is what your referring too.
If that's the case, then you will need to specify the Action's parameters for DoSomething() by specifying the route values like so:
#Html.Action("DoSomething", "Home", new {MyParam = 2} )
The result of DoSomething(int MyParam) would be injected into the page. Html.Action is not intended to call a POST so it's not possible to use this on an Action which has been decorated with the POST verb.
Issue was I was having one more ajax request to check if the page has been loaded completely to show progress bar, when removed that portion of the code from layout, It has been working fine without calling any action method twice.
I have an issue because I do not know how to call a specific method inside a Controller that is far away on the foler structure. I try to call it this way from my View
#Html.Action("Method", "DesiredControllerName", parameter)
I am pretty sure this works, because I am calling other methods from controllers this way. The only problem is that this time I need to reach a controller that is way up in a different folder, i.e.
The controller is in:
MySolution/Areas/Area1/Controllers/DesiredControllerName
Whereas the CurrentView Im making the call is in:
MySolution/Areas/Area2/Views/Client/CurrentView
How can I make the call work?
Thanks!
EDIT:
I found it,
As the controller is in another Area I just had to add it as a parameter
The controller for path was not found or does not implement IController
looks like you maybe got it, where your example code line:
#Html.Action("Method", "DesiredControllerName", parameter)
has the 'parameter' parameter, try using an array of anonymously typed routevalues and include an area and controller, something like this:
#Html.Action("Method", new { Area = "Area1", Controller =
"DesiredControllerName", })
I am used to using this style of providing mvc routing info using Html.ActionLink, but the Html.Action should be similar-ish. here is the msdn page for the Action method, hope that helps
#Html.Action("Method", "DesiredControllerName", new { Area = "Area1" })
This will works
What I am trying to do is to dynamically display welcome string of the company name based on url the area of "Your logo here" in MVC 4 Internet applcation.
So if I am in http://aaa.com I wanna to say welcome to aaa
What I have done is to replace
<p class="site-title">#Html.ActionLink("your logo here", "Index", "Home")</p>
to
#Html.Partial("_Company")
and in the _Company view I do #Html.RenderAction( "Company", "Home")
and in the HomeController I use
public ActionResult HospitalInfo()
{
var url = GetUrlMethod();
return PartialView("_Company ", new { name = url });
}
Can anyone please let me know if my idea is correct or not ? or can you help me to improve the method. Currently, my code does not work at all...
If you're only interested in a string, you don't need to spin up a separate partial view with its own controller action. Just create a helper function, manipulate the URL in there, and then call the function directly from your View.
.cs:
public static string GetCustomWelcomeString()
{
string customString;
// use System.Web.HttpContext.Current.Request.Url here to do the cool stuff
return customString;
}
.cshtml:
<p class="site-title">#MyClass.GetCustomWelcomeString()</p>
For a more architecturally clean solution, consider pre-calculating this title in the main controller action and returning it as a model field, so the view can consume it directly using #Model.CustomWelcomeString or something like that..
Try using the request object:
<p>Host is #Request.Url.Host</p>
You can split the URL however you want, but it doesn't need to go to the controller to get it
I ended up to use #ViewBag.CompanyName and created a base controller which all other controllers inherated from. And create a action method in which passing the company name string into #ViewBag.CompanyName.
So far so good.
I am calling a Controller Action from a view, within that controller I need to invoke another Action which I will invoke to save the view to a network location as either HTML or Image.
How do I retrieve the URL to an Action from within a Controller. Please note I need the actual URL, this means RedirectionToAction or View() wont work.
Why? I need to pass in a URL which will contain a call to a View. This view will be used to generate an image or HTML document using the System.Windows.Forms.WebBrowser.
.NET 3.5; C#; MVC 1;
I could do something like this, but its dirty ... well it leaves me with that dirty feeling.
using(Html.BeginForm("Action", "MyWorkflowController",
new {
MyId = "bla",
URLToGenerateImage = Url.Action("GenerateImage", "MyWorkflowController")
}))
I ended up using the MvcContrib.UI.BlockRenderer to convert to View to Html instead of generating the image. I proceeded to save the html string to a file system location.
Here is a link for further information
http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvc/
How about ContentResult - Represents a text result, so you could have
/Controller/GetUrl/id
Public ActionResult GetUrl(int id)
{
// builds url to view (Controller/Image/id || Controller/Html/id)
var url = BuildImageUrl(id);
return ContentResult(url);
}
in view you could have:
GenerateImage