在视图混合剃刀语法使用Javascript [英] Mixing razor syntax with Javascript in views

查看:114
本文介绍了在视图混合剃刀语法使用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是去了解它的正确方法。我需要它就像在下面的例子中工作。

 <输入类型=按钮值=恢复的onclick =window.location的='/Test?testid=@(ViewBag.TestID)'/>


解决方案

我是绝对支持,你应该使用ActionLink的这个具体的例子,以便有语义正确的标记Zabavsky的评论。

不过既然你问:


  

在视图中使用Javascript混合剃刀语法


从不这样做。

在你看来,你应该有唯一的标记:

 <输入类型=按钮值=恢复ID =myButton的数据URL =@ Url.Action(测试,新的{testid = ViewBag。 TestID})/>

和JavaScript(在一个单独的文件),您可以使用此标记工作,并悄悄地提升它:

  $(函数(){
    $('#myButton的')。点击(函数(){
        window.location.href = $(本)。数据(URL);
    });
});

当然,如果用户已禁用JavaScript的Web应用程序是完全捣毁。这就是为什么你应该总是写语义正确的标记。在这种情况下,这将是使用一个锚点,因为HTML按钮用于提交表单,锚被用来重定向到其他位置(这是您想在这个特定的情况下实现什么)。

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)'" />

解决方案

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).

这篇关于在视图混合剃刀语法使用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆