设置使用jQuery ViewBag值 [英] Setting up the value in ViewBag using Jquery

查看:1775
本文介绍了设置使用jQuery ViewBag值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想问问,有没有办法来动态建立viewbag值使用jQuery?
我试试这个code在我的剧本,

I just want to ask, is there a way to set up the viewbag value dynamically using jquery? I try this code in my script,

$(".btn").on("click",function(){
@ViewBag.Id = $(this).attr("id")
});

我不知道它的正确,但是当我尝试运行我的MVC 3项目,这个错误出现在我的萤火虫

i dont know if its correct but when i try to run my MVC 3 Project, this error appear in my firebug

Syntax Error
    = $(this).attr("id")

请帮助。谢谢

推荐答案

你误会ViewBag如何工作的。

You're misunderstanding how the ViewBag works.

在MVC工作时,你打开网页,这是(大约)发生的情况:

When working in MVC, and you open a webpage, this is what (roughly) happens:


  1. FooController的方法索引运行。最后,返回一个视图。

  2. 您的MVC应用程序,然后将找到的看法你,并开始按照它发现在相关.aspx文件的HTML渲染它。如果程序遇到诸如@ ViewBag.Id,它会基本上就一个字符串替换无论.ID值。 (这是比这更复杂一些,但对于参数的缘故,它基本上没有一个字符串替换)。

  3. 渲染之后,HTML文档发送到浏览器,谁再显示出来。

您的浏览器获取页面的时候,您的ViewBag已经基本消失了超出范围。这是因为你的ASP(MVC)应用程序使用ViewBag,但使用Javascript只有在Web浏览器文档中的一个范围内(这是被返回给浏览器的应用程序的HTML code 后ViewBag已超出范围即可。JavaScript是不是MVC应用程序的一部分,只有产生的网页。

By the time your browser gets the page, your ViewBag has basically gone 'out of scope'. This is because your ASP (MVC) application uses the ViewBag, but Javascript only has a scope in the web browser document (this is the HTML code that was returned to the the browser by the application, after the ViewBag has gone out of scope. Javascript isn't part of the MVC application, only the resulting webpage.

所以,简单的答案是,不,你不能那样做。尽量把它看成做一个内联字符串替换。
你只能把ViewBag值到HTML页面,而不是其他的方式。

So the short answer is, no you can't do it like that. Try to think of it as doing an inline string replace. You can only put the ViewBag value into the HTML page, not the other way around.

假设你的ID是5,在aspx文件如下code:

Suppose your Id is 5, the following code in the aspx file:

$(".btn").on("click",function(){
    @ViewBag.Id = $(this).attr("id")
});

将被发送到浏览器作为

Will be sent to the browser as

$(".btn").on("click",function(){
    5 = $(this).attr("id")
});

由于您的浏览器只能看到最后一部分,它只是没有在Javascript意义。在你的情况下,随着语法错误,它只是意味着你的变量尚未初始化,并且您试图访问

这篇关于设置使用jQuery ViewBag值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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