Mixing razor syntax with Javascript in views

2019-02-20 16:51发布

问题:

What's the proper way to go about it. I need it to work like in the example below.

 <input type="button" value="Resume" onclick="window.location = '/Test?testid=@(ViewBag.TestID)'" />

回答1:

I absolutely support Zabavsky's comment that you should use an ActionLink for this specific example in order to have semantically correct markup.

But since you asked:

Mixing razor syntax with Javascript in views

Never do that.

In your view you should have only markup:

<input type="button" value="Resume" id="myButton" data-url="@Url.Action("Test", new { testid = ViewBag.TestID })" />

and javascript (IN A SEPARATE FILE) where you could work with this markup and unobtrusively enhance it:

$(function() {
    $('#myButton').click(function() {
        window.location.href = $(this).data('url');
    });
});

Of course if the user has javascript disabled your web application is completely busted. That's why you should always write semantically correct markup. In this case that would be to use an anchor because in HTML buttons are used to submit forms, anchors are used to redirect to some other location (which is exactly what you are trying to achieve in this specific case).



回答2:

I would, as Zabavsky said, use an ActionLink for this:

Something like this:

@Html.ActionLink("Resume", "Test", new { testid = ViewBag.TestID })

There are quite a few overrides for actionlink, so you need to pick the one which fits your needs.

The one above output an a href with the text 'Resume' going to action 'Test' on the current controller, passing a routevalue of testid = ViewBag.TestID



回答3:

You can do it like:

<html><head><script>function newDoc()  {   window.location.assign("http://www.abc.com")  }</script></head><body><input type="button" value="Load new document" onclick="newDoc()"></body></html>

Hope it will help. Thanks.



回答4:

Well, what you wrote is valid. You may have VS underline your code in red cause it think you have a js error due to the '' string not ended... but if you run it, it works.

To avoid red underline, you could do :

@{string js = "window.location = '/Test?testid="+ViewBag.TestID+"    '";}
<input type="button" value="Resume" onclick="@js" />