Create a url that passes values to controller action - asp.net

I want to create a Url that I can email that goes to an action within a controller, passing to the action an Id and a Token. This is my code so far:
var action = new UrlActionContext
{
Action = "Verify",
Controller = "Auth",
Values = id, token
};
var url = UrlHelperExtensions.Action(action);
UrlHelperExtensions.Action is expecting an IUrlHelper however, and I have not been able to get this to work using that interface. Can someone please explain how I am able to form a Url that goes to this action?
I can only seem to find solutions to Asp.Net MVC projects, whereas I am using Asp.Net Core 2.0.

For ASP.Net Core 2.0 IUrlHelper is available as a property of the controller. ControllerBase.Url is an IUrlHelper instance. You should be using it like this:
var url = Url.Action(nameof(DoSomething), new { id = 10 });

Related

How to send and receive data between angularjs and asp.net mvc view

I have an application completed in asp.net MVC. I am using Visual Studio 2015 in conjunction with Microsoft SQL Server 2014. Now I am developing an App in ionic angularJS that will run on a different server. Basically I want to run my app and pull the same complete list from my asp.net application and display it in my app.
I have CORS configured so that isn't a problem.
My issue is with sending anything from my asp.net localhost to the angularJS http.get function which is running on a different locahostenter code here.
I am creating an object in my controller and passing it to my view. Then in my view i'm running the object through JSON.Encode and passing that to a variable. I want to grab that variable from the view and pass it to my ionic angularJS app.
I am new to asp.net MVC so please be easy on me! Thank you!
http get function in my angularjs controller.
$http.get('http://localhost:50384/EventsInformation/TestJsonIndex')
.success(function(data){
$scope.artists = data;
console.log(data);
});
object in my asp.net view. I just want to grab var data in my view and send it to angularJS http get function.
var TestMessage = ViewBag.Message;
<script type="text/javascript">
var data = #Html.Raw(Json.Encode(TestMessage));
</script>
Just in case you need to see my test object that I created in my asp.net controller.
public ActionResult TestJsonIndex()
{
EventsDetails TestEvents = new EventsDetails
{
EventsDetailsId = 1,
artist = "Test String",
ticketPrice = 34,
ticketsAvailable = 232
};
ViewBag.Message = TestEvents;
return View();
}
$http.get('http://localhost:50384/EventsInformation/TestJsonIndex')
.success(function(data){
$scope.artists = data;
console.log(data);
});
you console.log had no parameter passing through it and you could add your expression having that same controller using {{artists.anything}} since it is being attached to the scope artists. i hope this help though
And to send data through angular js to your asp.net api you will be needing this
$scope.addArtist = function(){
var data = JSON.stringify({
name: $scope.name,
songs: $scope.songs
)}
var config = { headers: {'Content-Type': 'application/json;charset=utf-8'}}
$http.post("http://localhost:50384/EventsInformation/TestJsonIndex",
data, config)
.success(function(data){
$scope.showMsg = true;
$scope.responseData = data.artists;
console.log(data.records);
})
}

angularjs get paramater from url

i'm currently working on a asp.net mvc site in which we are using angularjs for model binding. i have a controller setup but i need to grab the id from the url to pass it to the service. my url looks like:
http://localhost/myapp/section/5
I need to grab the 5 out of the url, we are not using angular for routing, is there anyway to grab that through angular? Otherwise i could use .net to inject that into a global js variable and use angular to read the id from there.
I setup my angular controller as below:
myModule.controller('SectionController', ['$scope', 'sectionRepository', '$routeParams', SectionController]);
function SectionController($scope, sectionRepository, $routeParams) {
var vm = this;
alert($routeParams.id);
the alert returns 'undefined', I'm assuming because I never setup the routes in angular, is there a way to do it without the setup of routes, as we don't want to use angular for routing.
You can use the $location service to grab the URL. From there, just parse it.
function SectionController($location) {
var url = $location.url();
//regex is slow, you should use substring/slice instead
//var regex = /(?:section\/)[0-9]+/;
var id = url.substring(url.indexOf("section/") + "section/".length);
alert(id);
}

Dynamic sitemap, database driven

I've been struggling with this for a couple of days now. Can't find any good example, or an example that I understand.
Background:
I own a small blog platform for user to blog.
Each user gets their own subdomain and for now there is no sitemap available. Not good.
I want to create some kind of dynamic sitemap, where all sitemapnodes is retreived from the database. The sitemap will be used only for the search engine spiders.
System: ASP.NET, mySQL.
The sitemap is pure XML. So I need in some way to create an ASPX file that return xml-data instead of html.
And I need to somehow redirect the web.sitemap to that dynamic file.
I have never worked with XML, and I dont know how to create a file that creates XML data. So i dont even know what to search for.
I don't want any static sitemap file to be stored on the server. Everything should be created on the fly.
So. Please. If you can give me some advise about XML, any example on the internet, or just what to search for.
My main questions:
1.
How to create XML output from aspx file?
2.
How do I "inform" the system, and search engine crawlers that the file to crawl is "/sitemap.aspx"
ThankS!
I looked into MvcSiteMapProvider.MVC5 and I could not get it to work. First of all it modified my Web.config to the point that my css and js files were getting a 404 not found when running my web app.
With the time I spent getting MvcSiteMapProvider to work I could have just wrote my own.
So... here is my own dumbed down version of generating a sitemap xml.
The only thing is you have to specify your routes manually. I haven't added reflection yet to go through each controller and pull out each action.
The data-driven piece works very well though.
In your Home controller add the action Sitemap and the private helper methods.
GetRouteUrls is the manually added controller/action routes.
GetDynamicUrls builds the data-driven Urls. In my example I have a LiquidsController and a Details(string id) action.
public ActionResult Sitemap()
{
var xml = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement("urlset",
new XAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
, GetRouteUrls()
, GetDynamicUrls()
)
);
return new XmlActionResult(xml);
}
private List<XElement> GetDynamicUrls()
{
var result = new List<XElement>();
using (var db = new ApplicationDbContext())
{
var liquids = db.Liquids.ToList();
foreach (var liquid in liquids)
{
result.Add(LocUrl("Liquids", "Details", liquid.FriendlyId));
}
}
return result;
}
private List<XElement> GetRouteUrls()
{
var result = new List<XElement>();
result.Add(LocUrl("Account", "Register"));
result.Add(LocUrl("Account", "Login"));
result.Add(LocUrl("Home", "Index"));
result.Add(LocUrl("Home", "About"));
result.Add(LocUrl("Home", "Contact"));
result.Add(LocUrl("Home", "TermsOfService"));
result.Add(LocUrl("Home", "PrivacyStatement"));
result.Add(LocUrl("Liquids", "Index"));
result.Add(LocUrl("Vendors", "Index"));
result.Add(LocUrl("Hardware", "Index"));
return result;
}
private XElement LocUrl(string controller, string action, string id = null)
{
if (!string.IsNullOrEmpty(id))
action = string.Format("{0}/{1}", action, id);
var baseUri = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
return new XElement("url",
new XElement("loc", string.Format("{0}{1}/{2}", baseUri, controller, action))
);
}
I then added a route so I could access the sitemap doing /sitemap
routes.MapRoute(name: "sitemap", url: "sitemap", defaults: new {controller = "Home", action = "Sitemap"});
The XmlActionResult return type can be found here:
Return XML from a controller's action in as an ActionResult?

ASP NET MVC Server Response to a basic ajax request

We have to make an ASP.NET MVC or ASP.NET application for basic ajax navigation in Customer.html of Notrhwind.mdb.
We have this 3 things:
A pure HTML/JavaScript form having HTML input text tags, one for each field of Customers table.
We have also 2 navigation buttons: NextRecord and PrevRecord having at OnClick() event : clientGetRecord(NextOrPrev)
A javascript ajax clientGetRecord function, something like this:
function clientGetRecord(NextOrPrev) {
var oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
var sURL = "ServerGetRecord.aspx?ID=" + NextOrPrev;
oXMLHTTP.open( "POST", sURL, FALSE );
oXMLHTTP.send();
var sResult=oXMLHTTP.responseText;
var aRecord = sResult.split(";");
document.getElementById('CustomerID').value = aRecord[0];
document.getElementById('CompanyName').value = aRecord[1];
document.getElementById('ContactName').value = aRecord[2];
document.getElementById('Adress').value = aRecord[3];
//... and so on ...
};
We must have something like a ServerGetRecord controler function which returns to the clientGetRecord function, a simple string containing the current record fields values separated by comma and using classic ADO database handling.
The question is : How to program and invoke the ServerGetRecord function? Can i have a VB code example of ServerGetRecord function (or ASPX, or ASHX, or something else?..) ?
Don't have any VB smaples for you, but you can create a controller (asp.net mvc) that returns a JsonResult. You get your data from the DB and build the JsonResult object to return.
Then on your client use jQuery to call the controller and get the results as json format.
This post can help you get started: Link
Hope this helps

Creating a URL in the controller .NET MVC

I need to be able to construct a link in the Action on the controller to send an email. What is best practice to do this? I don't want to construct it myself in case my routes change.
Should I have a view for each email and render that and send it? That might be a good way of doing it.
If you just want to get the path to a certain action, use UrlHelper:
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);
if you want to create a hyperlink:
string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);
Intellisense will give you the meaning of each of the parameters.
Update from comments: controller already has a UrlHelper:
string url = this.Url.Action("About", "Home", null);
If you need the full url (for instance to send by email) consider using one of the following built-in methods:
With this you create the route to use to build the url:
Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
Here the url is built after the route engine determine the correct one:
Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
In both methods, the last 2 parameters specifies the protocol and hostname.
Regards.
I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.
My solution looks like this:
string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });
This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.
EDIT: I found this useful as well.
Another way to create an absolute URL to an action:
var relativeUrl = Url.Action("MyAction"); //..or one of the other .Action() overloads
var currentUrl = Request.Url;
var absoluteUrl = new System.Uri(currentUrl, relativeUrl);
I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:
var urlHelper = new UrlHelper(this.ControllerContext);
Or, you could just use the Controller.Url property if you inherit from Controller.

Resources