How to make a variable in the razor view global? [

2019-09-19 16:20发布

问题:

I want to know how to make a variable that I declare in a razor view global so that I can access it in another view? I performed an ajax function that fetches the location of a td element in its parent table. I then stored the index in an int variable. Now I want to access that variable from another view/controller to complete an if-else statement. How do I do this?

回答1:

The best way to do this (although it's not exactly a great idea in the first place) would be to pass your variable that you want to be global to the next views view-model, then just access it using @Model.Member You could also use a cookie, session variable, and a slew of other things, then when you need to use the variable, just read the value from the session or cookie you stored it in.

My advice is if you feel you need to use a view-global variable...you probably need to re-think the problem you're trying to solve, because there is likely a better way to do it.



回答2:

If you're getting the value via AJAX, then that means that the server has already rendered and returned the response. At this point, there's no such thing as "views" any more. You just have an HTML document, or rather a representation on an HTML document called the DOM (Document Object Model). If you need to utilize this value in so other controller action/view, then you need to pass it along with the request for that controller action/view, since the only way to do anything new server-side at this point is to send a request to the server.



回答3:

Why not set a javascript variable to to the value you want to access and so long as the page doesn't refresh or redirect using javascript from the other view should be able to find it. Use window.myVariableName to help widen the scope of the javascript looking for the variable.

If your page redirects or refreshes, this would not be a viable solution.



回答4:

Create a custom WebViewPage:

public abstract class CustomWebViewPage : WebViewPage
{
    public string Foo { get; set;} //Provide your Variables here
}

And register it in your /Views/web.config

<pages pageBaseType="Your.Namespace.CustomWebViewPage ">

More details here