Get URL of current page in C# with AngularJS - c#

I am working on tracking system for my SignalR Hub purpose. For this I have class where I want to store URL which will represent current page where user is, then his last request since I use paged list for my data tables and I need to know exactly on which page user is and of course user id.
This is my class where I want to store information
public class UserTracking
{
public string URL { get; set; }
public string LastRequest { get; set; }
public string UserId { get; set; }
}
Since I have a single page application I have problem with tracking user position on website because of angular routing, but for displaying views I have dashboard controller with ActionResults methods to allow me to display .cshtml pages with angular routing, something like this below
public ActionResult ProjectTask()
{
return View();
}
public ActionResult Project()
{
return View();
}
My question is if I am able somehow to get URL of user position on my website. For example if user is on http://localhost:2969/Dashboard#/tasks/ I want to get this /Dashboard#/tasks. Maybe I can get some information from my ActionResults, but I have no idea how.

It is hard to know if this will work for you with the information you've provided, but the following could work.
If you know the specific routes that a user must navigate to to reach you MVC Controller then you could pass in that information as a model when you return the view. Say I have an MVC route that is meant to return a Razor page that displays all the items from my list named "Freddy's Birthday". The URL in this case would look something like:
localhost/list/Freddy's%20Birthday
matching a route:
[Route("~/list/{id}")]
To inform Angular of what you're dealing with, simply pass in the information as a model:
public ActionResult List(string id)
{
return View(model: id);
}
You can access that model in your cshtml with #Model. If the id passed in was "Freddy's Birthday" like before:
<div todo-list-item-directive>#Model</div>
Would return from ASP as:
<div todo-list-item-directive>Freddy's Birthday</div>
This way works, and you could build some view models to reference in your Razor pages if you need to pass in more complicated information. However, if at all possible, it'd likely be worth your while to set up ui-router and use Angular for your view routing and ASP.NET for your API.

Related

How do I send form data to HttpPost Action with Postman in ASP .Net Core MVC

Out of simple curiosity I would like to Post data from my MVC app to my local database with Postman. Unfortunately, I encountered a certain obstacle and cannot figure out how to solve it.
The general idea is that I have a controller X with an Edit method accepting YViewModel as the only parameter.
XController : Controller
{
//Post
IActionResult Edit(YViewModel vm)
{
//Code
}
//Get
IActionResult Edit(int id)
{
//Code
}
}
YViewModel
{
public int Id { get; set; }
//Other fields below
}
In the Edit method with an HTTP GET Verb I am returning the respective view with the YViewModel containing all the required fields. All the fields (except Id) are assigned to form inputs.
The Id is only bound to the VM model. Binding works perfectly on the page, but I cannot compose the right Postman Request.
I know that I can try localhost..../X/Edit with form-data and then assign all the form fields. But where do I fit Id in that request?
Under the Body tab select x-www-form-urlencoded. For Key use Id. For Value use whatever you want to test with.
I assume you would want to post other YViewModel fields for testing.
Ensure you are creating a POST request.
If Id as the Key doesn't work you can load the page in your browser and look for the name attribute of the Id hidden field. Then use that in Postman.

ASP.Net WebForms User Controls With Code Behind In MVC

I'm trying to move from the Old WebForms .NET approach to the newer MVC version. I just can't seem to find a solution to this issue.
In my current projects I use a lot of custom made User Controls. These controls will in almost all cases have several properties that are populated as parameters in the code behind of the parent 'aspx' page.
The User Control will have an 'ascx' page where all the html and controls exist. There will also be a 'ascx.cs' file attached to it where all the properties, methods and back-end logic occur.
What I can't seem to work out is how this logical process works in MVC? The .ascx file is similar to an MVC PartialView... that does make sense.
But where do you store all the backend logic for a PartialView?
How do I set multiple properties and construct the View based on these values?
I've seen some people suggesting you can still use .ascx files in MVC but I'm not sure this is the correct route to go down... certainly not the best practice route anyway?
I'll give a small example which may help:
country.aspx
<%# Register tagprefix="CUSTOM" tagname="Weather" src="~/controls/Weather.ascx" %>
<CUSTOM:Weather ID="Weather" runat="server"></CUSTOM:Weather>
country.aspx.cs
Weather.W_CountryCode = CountryCode;
Weather.W_CountryName = CountryName;
weather.ascx.cs
public string W_CountryCode { get; set; }
public string W_CountryName { get; set; }
Ok that is very basic structure of a control.
The control is embedded into the parent page.
Parameters are set in the code behind of the parent page.
The properties in the control will be used to collect the selected countries weather data from the database as well as running various other methods.
This easily reusable self contained code... I just can't see how you do the same thing in MVC? Where do you set the parameters... where is the code behind for the View stored?
Thanks in advance for any help
When you create a "page" in MVC, you have a controller action that builds a model and passes it to a view.
A "partial" page works exactly the same way - you have a controller action that builds a model and passes it to a view.
The only difference is that the action returns View() or PartialView().
When you want to re-use the partial, you can do so in two ways - load via the action or load via the partial. When you load via the action #Html.Action, you call the controller-action (perhaps with parameters) and that action builds the model and returns the (partial) view. When you load via #Html.Partial your view passes the model to the partial directly (ie not via a controller). Either is acceptable, it depends on how you are building the partial and whether you've already loaded some data or not etc.
So, for your example:
StaffViewModel.cs (partial)
public string W_CountryCode { get; set; }
public string W_CountryName { get; set; }
Staff.cshml (partial)
#model StaffViewModel
<div>Country: #Model.W_CountryCode / #Model.W_CountryName</div>
CountryViewModel.cs (view)
public IList<StaffViewModel> StaffList { get; set;}
Country.cshtml (view)
#model CountryViewModel
#foreach (var staff in Model.StaffList)
{
#Html.Partial("Staff", staff)
}
Controller.cs
public ActionResult Country()
{
var model = new CountryViewModel();
model.StaffList = new List<StaffViewModel>();
// populate staff list from DB etc here
return View(model);
}

Different start layouts for different user types with asp.net mvc

I have three types of roles for each of the menu links.
When the Billing guy is logging into the site
how can I determine dynamically the partial.html file that is shown in the content area?
I can not hardcode the content to the first actionlink in the menu, that means that always the Administration is loaded initially.
What can I do in such a case?
These types of decisions are best made in the Controller.
Example:
public HomeController: Controller
{
public ActionResult Administration()
{
// Determine the user's role.
// "GetRole()" does not really exist on the controller - use your own method.
string role = GetRole();
if (role == "Billing Guy")
return View("AdministrationBillingGuy")
else if (role == "SalesGuy")
return View("AdministrationSalesGuy")
else
return View();
// etc.
}
}
I can think of several ways to do this.
if you need all users to get the same url/action then you could do something like this
public ActionResult Custom(RoleEnum userRole)
{
switch(userRole)
{
case RoleEnum.Admin:
.....
return Partial("_adminPartial", viewModel);
// rest of you cases here
}
}
OR:
public ActionResult Custom(RoleEnum userRole)
{
var view = GetViewByRole(userRole);
// where GetViewByRole takes the enum and
// returns a string with the name of the partial
return Partial(view, viewModel);
}
Another way to do this is, and one that I'd recommend is to make an MVC Area for each user requiring a different layout and then at login you can redirect them to the proper Area, I recommend it because it allows for deeper differentiation between roles in the UI layer.
Another way to achieve the different layouts (am talking about MVC Layout Pages similar to ASP.Net Master pages) is to pass a string Layout to the view, using the ViewBag or any other method you like, then in the Razor code you could do something like this:
#model MyViewModel
#{
Layout = (string)ViewBag.Layout;
}
I leaved this last one for last as it appears a bit hacky to me. Hope this helps you
Well, you haven't provided enough information give any explicit direction, but generally, you should just alter your login post action to redirect to a different place depending on some identifying factor like a role (following is pseudocode)
// do login
if (user is "Billing")
{
// redirect to billing action
}
// etc.
The only reason you should be switching out partials or views is if you're doing a SPA (single page application) and utilizing JavaScript for routing. In that case, you would just need some endpoint you could hit with AJAX to get the user's "role".
However, I don't think that's what you're actually doing. If you're just using MVC directly, then you should be actually changing the URL, not just loading a different Razor view.

ASP.NET MVC 4 Make a page not directly reachable

I have a ASP.NET MVC 4 Blog which is 90% done but i need one thing - i have a webpage lets say index/secretPage but i want to be able to navigate to this webPage only after i am redirected from another - lets say index/redirect . If the adress is hardcoded it should not navigate, if the visitor is coming from a different link like blog/post/24 it should not be able to navigate too.
I hope my question was clear, than you for all help.
You could also mask the secret page with an action that shows another page if direct called.
In this example there are 2 actions. 'Secret' for returning a bogus view and the 'Check' for the real call. In this action the bool variable 'allowSecret' ist checked an then the user sees the view 'secret.cshtml' if allowed or 'index.cshtml' if not.
Here's an example code for a simple controller with that functionality:
using System.Web.Mvc;
namespace Test.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Index");
}
public ActionResult Check()
{
// check if user is allowed to show secret page
if(allowSecret == true)
return View("Secret");
// Otherwise return view 'index.cshtml'
return View();
}
public ActionResult Secret()
{
// Always shows view 'index.cshtml' if url is ".../secret"
return View("Index");
}
}
}
You could also redirect to another action after the check fails instead of calling a 'fake-view':
return RedirectToAction("Index")
The difference is the url the user sees in the browser. Returning a view does not change the url, redirecting to another action changes the url to the changed route.
Of course you can place the check in another class behind the controller.
Another option is to use the 'NonAction' attribute:
[NonAction]
public ActionResult Check()
{
...
}
Hope that helps with kind regards,
DD
You can UrlReferrer to get to know who refred to this current page and throw and exception or redirect back
HttpContext.Current.Request.UrlReferrer
http://msdn.microsoft.com/en-IN/library/system.web.httprequest.urlreferrer.aspx
But for what ever reason you need this. It dosenot look like a good design to me.
Hope this helps

Share an object application-wide in ASP.NET MVC3

I have an ASP.NET MVC3 web application with C# and Razor.
Through a form in a View I get the Context.User.Identity.Name submitted to an action method in a Controller A.
I would like to have available this variable application-wide (between multiple controllers).
Now I am just able to assign it to a global variable _UserName within the Controller A, but of course it is not available in Controller B.
Is it possible to do that?
Thanks
Francesco
If you are accessing this in any controller, you should use HttpContext.User.Identity in your controller methods - it will be available there. No need to store in the session.
Create a parent controller from which all your controllers inherit from and set the variable there. You could do a number of things with it from there--wrap it in a view model, put some user details into the ViewBag, etc
public class UserController : Controller
{
// create your own User class with as many properties as you need
protected User user { get; set; }
public UserController()
{
user = // get user from db, wherever
}
}
Then, just inherit from UserController
public class ControllerA : UserController
{
public ActionResult DoSomething()
{
user.Property = 123;
}
}
You should look into caching and possibly using the users session store this information.
Check out this question.

Categories