How to convert javascript variable to a Razor variable? - c#

lets say i have a javascript variable such as:
var something = "information";
I now want to do things with this variable in Razor
#string something2 = something;
I would like to do something similar to the above code, any ideas?

You wont be able to convert JavaScript variable to a Razor variable. Where Razor variable is handled by Razor engine where as JavaScript on the other hand is a client side language running on the client.
Razor is a view engine used by the ASP.NET MVC framework running on the server to produce some HTML template.

Related

ViewBag in View without #

I don't get why we sometimes use ViewBag without reference (I mean #) to Controller in View, e.g.:
#{
string urlFilter = Url.Action("Index", "Home", new
{
CustID = ViewBag.custid,
Errors = ViewBag.errors
});}
It looks like a part of c# code in view. I know that razor synthax allow us to inject c# code into View but don't understand what's the point of using ViewBag without # in View
In this case it is because it is within the scope of a C# code block (#{ ... }) and not in the HTML markup.
If however, you were trying to reference the ViewBag inline in an HTML block you would need to prefix it with # to make sure it was processed by the Razor engine.
for example:
<p>#ViewBag.Name</p>
ViewBag is a dynamic property on the WebPageView from which the view is derived.
You can learn about the Razor syntax here: https://learn.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c

C# ASP.NET Core Razor pages: How to access route constraint within markup

I have a Razor page with the markup starting like so:
#page {id:int?}
...
Now, if you access the page on a path /MyPage/5 the id parameter on the class method OnGet(Int32? id) will be set to the value 5.
I'd like to display some conditional markup depending on the value of the id, is there a way I can access the id in the markup directly?
I tried #id but it says it isn't defined - which makes sense I guess.
I figured I could catch it in the OnGet(..) method and make it available through a property if there is no other way to do this directly. The downside to this approach is that I have to re-set the value every time a post-back happens.
Is there a way to do this?
Short Answer
Here is one way to access the id value.
<p>RouteData.Values["id"]</p>
Debugging
If you want to debug you can dump all the available RouteData on the page like this:
<p>#Newtonsoft.Json.JsonConvert.SerializeObject(RouteData)</p>
The output will look something like this:
{"DataTokens":{},"Routers":[],"Values":{"page":"/Index","id":"101273123"}}

How can I simply parse a stand-alone razor template and use the output as an email body in c#?

I've looked at a dozen or so ways to do this and I'm having a very hard time getting things to work. The issues I've run into fall into one of two categories:
1) A full MVC setup is assumed in the examples I'm looking at. In my case, I'm sending an email from a WebApi project and will not be using any of the pre-wired MVC view functionality provided by the ASP.NET project stub.
2) Libraries are asking for some complex setup I don't really think I need, specifically RazorEngine asking me to set up a TemplateManager, when all I need to do is give a .cshtml file a model and get the parsed results back.
Pardon the noob question; I'm working on my first .NET project here. Thanks!
I had to do the same thing for different reasons a while ago. I had found this class that I used to render the view into a string: https://github.com/RickStrahl/WestwindToolkit/blob/master/Westwind.Web.Mvc/Utils/ViewRenderer.cs
Use it like this:
var r = new ViewRenderer();
var renderedView = r.RenderViewToString("~/Views/MyView.cshtml");
If you need to pass a model to the view, call it like this:
var renderedView = r.RenderViewToString("~/Views/MyView.cshtml", model);
Where model is what your view expects.

Razor convetions

I have been working a Razor templeting system but am running into a consistent syntax error. In many of my .cshtml files I am swapping between .cs and .js multiple times on one line of code which causes the intellisense get confused.
Example
<script type="text/javascript" id="dtscript">
///...
#if (!string.IsNullOrWhiteSpace(ColumnDefs))
{
#:columnDefs: #model.ColumnDefs,
}
///...
</script>
In the above line the trailing comma after #ColumnDefs is a syntax error, however when the .cshtml file compiles and I render the template the rendered code is correct. This syntax error holds for alternate ways of generating the code...
#if (!string.IsNullOrWhiteSpace(ColumnOrder))
{
<text>order: #model.ColumnOrder</text>,
}
//or
#if (!string.IsNullOrWhiteSpace(ColumnOrder))
{
<text>order: #model.ColumnOrder,</text>
}
Since the template generates the correct view I have been slow about addressing the syntax error, but I am getting tired of all of the red squiggly lines. So my question is what is the correct way to splice .cs and .js to avoid incorrectly reported syntax errors throughout the razor file.
Update:
Let me expand on this scenario a little. There is no controller, this system is a stand alone library. The templeting system is product agnostic and is part of a Domain Specific Language for common plugins. The #model.ColumnDefs is actually a json object that renders into the following code.
columnDefs: [{"sortable":false,"targets":[0,3]},
{"visible":false,"targets":[0,7]},
{"searchable":false,"targets":[0]},
{"name":"Id","targets":0},
{"name":"Email","targets":1},
{"name":"Name","targets":2},
{"name":"IsAdmin","targets":3},
{"name":"Salary","targets":4},
{"name":"Position","targets":5},
{"name":"Hired","targets":6},
{"name":"Number","targets":7}],
It can not be wrapped in "" or '' otherwise the plugin is not able to parse the code.
You should move most logic to the controller. Which means the line:
#if (!string.IsNullOrWhiteSpace(ColumnOrder))
should be inside the controller:
if(!string.IsNullOrWhiteSpace(ColumnOrder)) ViewBag.Something = ...;
In razor, initiate your desired state as javascript variables:
var something = "#ViewBag.Something"; //this is a javascript line
In my experience, Visual Studio's intellisense work correctly in this case and identifies #ViewBag.Something as a razor syntax (but note the double quotes, they belong to javascript, which encloses the string value).
Currently this syntax error issue is known and marked as Deferred.
https://connect.microsoft.com/VisualStudio/feedback/details/760339/valid-javascript-razor-syntax-marked-as-syntax-error
Using the suggested workarounds are good enough for now.

Converting JavaScript variable to C#

I have a variable in JavaScript and I want to use it as an index reference in my C# code. How do I convert the JavaScript variable into something C# can use? So far this is what I have..
#{
var selectedStockLocation = #Html.Raw(Json.Decode(document.getElementById("cbLocation " + id).value));
var currentLocation = Model.StockLocationBinData[selectedStockLocation];
}
You will have to post the value back with either a full POST or an AJAX call.
You are mixing server and client code there.
You need to use (one of many) methods to post client data back to the controller.
Use jquery to write to a hidden variable in the form is one route, see this answer:
Passing a jQuery value to MVC 3 Razor view html helper
JavaScript runs well after the server-side code has rendered and completed; you cannot use it while rendering the view.. You can, however, store the value in a hidden field, put this hidden field in a form, and process it during a post operation. Or, send it to the server via an AJAX callback.

Categories

Resources