Call a controller action on click of hyperlink when javascript disabled - c#

I have a cshtml with below code,I want to record the link which was clicked by the user,The link might be a external url.This should work even when javascript is disabled.
foreach (var featuredPod in Model.FeaturedPods)
{
Find out more
}

If you want to record what the user clicked , then you will need to process this on the server and redirect the user to the real link
So something like (assuming each featuredPod in the model has some form of Id)
#Html.ActionLink("Find out more", "RecordAction", "RedirectController", new {Id=featuredPod.Id}, new {#class="", target="_blank"})
Then in the RecordAction action in the RedirectController
// get your Model.FeaturedPods where Id = passed in id
// record what the url is somewhere
Return Redirect(featuredPod.LinkUrl)

Can't you just use #Html.ActionLink helper?
#Html.ActionLink("Find out more", "Action", "Controller", new {Id=Model.Id}, new {#class="(...)"}

Related

How to open new window from MVC using RedirectToAction?

I want to open View throe controller using RedirectToAction, how to open new window?
public async Task<ActionResult> RepINVPurchaseAbstract(PAbstract ObjPAbs, string ButtonValue)
{
return RedirectToAction("ReportDisplay", "Common", new { area = "" });
}
Any help would be appriciated.
It is impossible to return a result of a action to a new window, as the action was called from origin one and origin one waits for response. What I would do, is open a new window first, with specific parameters (either in URL or in JavaScript event body.onload that perform your action and return result directly to new window.
Lets assume your link or button or whatever looks like this:
#Html.ActionLink("ActionName", "Controller")
add target="_blank" to you to open it in new tab or window (depending on what browser you use and what browser configurations are set):
#Html.ActionLink("RepINVPurchaseAbstract", "YourController", null, new { target = "_blank" })
It will redirect to your RepINVPurchaseAbstract action method then will redirect to your "ReportDisplay" action and will render out your view.

Get Html.DropDownList Value in a Controller Function MVC

I need to get the selected value of a dropdownlist when I click an ActionLink.
Here is the dropdownlist I am binding from controller.
#Html.DropDownList("resource", new SelectList(ViewBag.ResourceList, ViewBag.SelectedResource), "Resource", new { #class = "span6", #style = "width:14%; color:black;"})
And ActionLink with the function without [HttpPost]
#Html.ActionLink("Export Data", "ExportData");
I have tried from Request.Form["resource"] but it gives me null all the time
public ActionResult ExportData()
{
var req = Request.Form["resource"];
}
I just need to get the text value whatever is in the DropDownList inside my ExportData Function.
The action link basically renders an a tag, and the a tag will look something roughly like this;
Export Data
Because links issue a GET request, any parameters need to be passed via:
Export Data
Request.Form will always be empty in a get request because a POST request populates the form collection. But either way, with a GET or POST request, you can pass the data as a parameter of the action method like:
public ActionResult ExportData(string resource)
So either put a <form> around the data you want to post to the server and change the hyperlink to a button to initiate the post, or use javascript to append "?resource=VAL" to the end of the hyperlink HREF attribute, where VAL is the value from the dropdown.
EDIT: in the few scenarios I had to do this before, what I'll normally do is on the link, add a data attribute (in C# API, use data_ for data attributes):
#Html.ActionLink("Export Data", "ExportData", new { data_url = "ExportData" })
The reason why I use a data attribute is to preserve the original URL and that way I don't have to do string manipulation. Using jQuery, on resource value change, you can update the URL easily:
$("#resource").on("change", function(e) {
var val = $(this).val();
var href = $("#linkid").data("url") + "?resource=" + val;
$("#linkid").attr("href", href);
});
Anytime the dropdown changes, it updates the link url.
You should try the GetValues() method:
public ActionResult ExportData()
{
var req = Request.Form.GetValues("resource");
}

Asp.net mvc Url.Action to redirect controller with nullable parameters

I have controller like this:
public ActionResult Load(Guid? id)
{
...
}
When load the view like /Report/Load it load the page.
Then I click on link on page to load one item /Report/Load/7628EDFB-EFD5-E111-810C-00FFB73098ED and it loads the page fine.
Now I want to redirect again to /Report/Load using this url.action
Close Report
But it keeps redirecting me to /Report/Load/7628EDFB-EFD5-E111-810C-00FFB73098ED
What I need to do on URL.Action to redirect me to page with the id?
Tried without success:
Close Report
Thanks
Use:
Close Report
See this answer for more details.
I got it fixed by following answer from johnnyRose and Beyers.
The result is
Close Report
Thanks a lot.
I can't seem to find issue with your code. But Can't you simply set the URL in the model when trying to load the specific item.
In the load function inside the controller do something like this:
var urlBuilder =
new System.UriBuilder(Request.Url.AbsoluteUri)
{
Path = Url.Action("Load", "Report"),
Query = null,
};
Uri uri = urlBuilder.Uri;
string url = urlBuilder.ToString();
YourModel.URL = url;
In your view.cshtml do something like
reports
You should have looked up in your vs's intellisense-
As it accepts arguments- ActionName,ControllerName,RouteValues
Where routeValues is the third argument that is object type and it accepts route values i.e. new{id=9,name="foobar"}
Where method would be like-
[HttpGet]
Public ActionResult Get(int id, string name)
{
}

Html.ActionLink to call an action from a different controller that's in a different folder

I've got a simple view that creates a link if a login is successful and is located under /Login:
<div>
#Html.ActionLink("Add a new Organization", "AddOrganization",
"/Setup/AddOrganizationController", new { id = Session["ID"] }, null)
</div>
After reading other similiar problems, I tried it adding the null after, as well as a few other overloads, but I can't get the link to work right. When I click the link, it takes me to
http://setup/AddOrganizationController/AddOrganization
Which is leaving out the localhost part that needs to be there. Without the null at the end, it tries to send me to
/Login/AddOrganization
All I want is a link that will run an action within the AddOrganizationController controller which is under /Setup directory. The link should also pass the session id to the controller as an argument. How can I do this?
If it's in the same Area then you can just do:
#Html.ActionLink("Add a new Organization", "AddOrganization", "Organizations", new { id = Session["ID"] })
where "Organizations" is the controller name.
Otherwise, if it's in another area you would do something like
#Html.ActionLink("Add a new Organization", "AddOrganization", "Organizations", new { area = "areaName", id = Session["ID"] }, null)

Url.Action and two variables

I have #Html.PagedListPager(Model, page => Url.Action("GetTabData", new { page })
and inside my js file I have ready to use myTab variable which I need to send together with page in above example.
How can I do that?
Update:
I'm using js variable to determine which tab is user click and based on that value I'm quering data. Now I have implemeted pagination which uses above generated link. With this in place my ajax call for sending activeTab is broken, I need to send this value together with page inside above Url.Action.
This is js variable which I use to send over ajax to determine which tab is user click
$(function () {
var activeTab = null;
$('#tabs .tabLink').click(function (event) {
var activeTab = $(this).attr('href').split('-')[1];
GetTabData(activeTab);
});
GetTabData(ommitted on purpse)
});
I don't get the question clearly, but I am taking a guess here. Don't know if this is what you are looking for.
Note - You have GetTabData in both your javascript as well as cshtml code, I am hoping this is just coincidence, because the js function cannot be invoked via #Url.Action in this manner.
If you need to send two values as part of your URL, you could do it either in a RESTful way or have querystrings.
Option 1 -
Url.Action("GetTabData", new { page=2, tab="blah" })
Your corresponding controller action would look like
public ActionResult GetTabData(int page, string tab)
{
...
}
Option 2 -
create a querystring and append it to the URL
/GetTabData?page=2&tab=blah
In this case the controller action would look like this
public ActionResult GetTabData()
{
var params = Request.QueryString;
...
}

Categories

Resources