Reputation: 39298
Please note that it's the opposite of the usual question.
I have a function that adds a score to a control recognized by a certain guid. The problem is that the upper limit is stored in the model of the Razor page. I need to get to it using the guid that I've got from my button's ID.
@Model.Answers.Single(=>.Id==HERE BE THE JS GUID).Max
The guid is $(invoker).attr("id").substr(3)
The code of the function looks like this. I can'f for my life figure out the syntax to get it it there.
function adjustScore(invoker, delta) {
var target = $("#val" + $(invoker).attr("id").substr(3));
var newValue = +target.html() + delta;
var max = @Model.Answers.Single(_=>_.Id == new Guid()).Max;
if (newValue < 0 || newValue >= max)
newValue = 0;
target.html(newValue);
}
Upvotes: 0
Views: 1210
Reputation: 218942
Razor code gets executed in the server and razor sends the generated output to the browser. Your javascript will be executed at client side. So in short, you cannot mix those as you tried.
What you can do is, have your server code in an action method in your controller and use ajax to call this method, pass the javascript variable values you need and use it.
function adjustScore(invoker, delta) {
var target = $("#val" + $(invoker).attr("id").substr(3));
var newValue = +target.html() + delta;
$.get("@Url.Action("GetMax","Home")",function(max){
if (newValue < 0 || newValue >= max)
newValue = 0;
target.html(newValue);
});
}
Assuming you have a GetMax
action method in your HomeController
which returns the max value as decimal value.
public decimal GetMax()
{
// query your data and return a decimal
}
I am using Url.Action
helper method to generate the correct relative path to GetMax method. If your code is inside an external javascript file, use the approach mentioned in this post.
Upvotes: 1