1

I'm working on a project using C# razor engine and I wondering if it is possible to merge razor syntax with jQuery. Is that possible?

An approach I have done is something like this:

<script>
    $(document).ready(function() {
        @Html.Action("GoNext", "Actions", new { Id= ViewBag.Id, justifymessage = @:$("#msg").val(), Action = 3 })
    });
</script>
2
  • 1
    not 100% positive but if somebody knows I'd like to know as well. I believe the correct syntax would be to write out the html and append it somewhere w/ jQuery. something like a href="youAction">click me</a> and append that. I don't think you can use MVC from within jquery scripts, but I could be wrong Commented Jun 11, 2015 at 11:38
  • @Html.Action is server side. $("#msg").val() is client side. Commented Jun 11, 2015 at 11:41

2 Answers 2

1

Razor is server side while jQuery is client side. You can merge them... You may only write a razor code inside jQuery but razor will render it result before jQuery.

To call an action from server, use Ajax. See what you can do

 <script>
   $(document).ready(function() {
      var url="@Url.Action("GoNext","Actions", new {Id= ViewBag.Id, Action = 3 })";
      url+="&justifymessage = "+$("#msg").val();
      jQuery.get(url).done(function(htmls){
            jQuery('#appendable').html(htmls);
       });
   });
 </script>
 <div id='appendable'></div>
Sign up to request clarification or add additional context in comments.

Comments

0

if say, you want to redirect to that url try:

<script>
$(document).ready(function() {
    var yoururl = "@Url.Action("GoNext", "Actions", new { Id= ViewBag.Id, justifymessage = "#param#", Action = 3 })";

    location.href=yoururl.replace("#param#", $("#msg").val());
});
</script>

2 Comments

the only other consideration would be the appropriate encoding of $("#msg").val()
do you mean Url.Action?? I don't think Html.Action will do

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.