0

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);
}
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • Razor code is server side and is evaluated before the view is sent to the client. A javascript variable does not even exist at that point. –  May 08 '16 at 22:47
  • If the Razor code generates the button then it can also generate the limit that can be used by JavaScript. – Tom Blodget May 08 '16 at 23:35

1 Answers1

1

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.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497