0

Is it possible to insert a c# variable into a inline javascript function?

I'm using razor to pass the select boxes id.

<select id="@itemid" style="float:right" class="input" onchange="window.location.href='@url3' + 'booking/' + '?d=' + '[email protected][[email protected]].value">
</select>

The above does not work. I get a "does not contain a definition for 'form'" error.

2 Answers 2

1

Try with this

onchange='@("string.format("window.location.href='{0}' + 'booking/' + '?d=' + 'this.form.{1}.options[this.form.{1}.selectedIndex].value", @url3, @itemid))'
Sign up to request clarification or add additional context in comments.

1 Comment

The explicit expression block is missing a closing ")" character. The function above works ok, inline would have been nice.
0

Yes. You can use Razor syntax in javascript as long as it is in the view file.

I prefer to keep the markup clean without the behavior(separation of concern) and keep that behavior in unobtrusive javascript way. I would keep a HTML 5 data attribute to set the value of url3 variable.

<select id="@itemid" style="float:right" class="input" data-targeturl="@url3">
</select>

and in javascript, listen to the change event of SELECT element with .input class and redirect to the new page

$(function(){

 $("SELECT.input").change(function(e){
   var _this=$(this);
   var newUrl=_this.data("targeturl")+"/booking?d="+_this.val();
   window.location.href=newUrl;
 });

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.