Javascript 在模型对象上设置属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5181151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting property on the model object?
提问by Banshee
Hi,
你好,
I am building a ASP.NET MVC site and have runned across a problem. In my project I got a modelview class that contains a couple of properties, for example :
我正在构建一个 ASP.NET MVC 站点并且遇到了一个问题。在我的项目中,我得到了一个包含几个属性的模型视图类,例如:
public class myModelView
{
public int MyProperty1(){ get; set;}
public int MyProperty2(){ get; set;}
public int MyProperty3(){ get; set;}
}
This modelview class is bound to a typed view where I need to be able to set the properties. How do I do this with javascript/jquery? I have tried with Model.MyProperty1 = 1, but that does not work?
这个模型视图类绑定到我需要能够设置属性的类型化视图。我如何使用 javascript/jquery 做到这一点?我试过 Model.MyProperty1 = 1,但这不起作用?
BestRegards
此致
回答by Darin Dimitrov
You cannot set server side values with javascript. You could bind those values to input fields (textboxes, hidden fields, textareas, dropdowns, ...) using HTML helpers and then using javascript you could modify the values of those input fields.
您不能使用 javascript 设置服务器端值。您可以使用 HTML 帮助程序将这些值绑定到输入字段(文本框、隐藏字段、文本区域、下拉菜单等),然后使用 javascript 修改这些输入字段的值。
So for example if you have a hidden field:
例如,如果您有一个隐藏字段:
<input type="hidden" name="foo" id="foo" value="bar" />
you could modify its value like this:
你可以像这样修改它的值:
$('#foo').val('some new value');
Then when the containing form is submitted to the server the new value will be bound to your view model.
然后当包含表单提交到服务器时,新值将绑定到您的视图模型。
回答by Jakub Konecki
You are trying to set the server-side property on the client - it won't work. Your view model exists only on the server when your view is rendered. Once the response is sent to the browser your class doesn't exist any more.
您正在尝试在客户端上设置服务器端属性 - 它不起作用。当您的视图呈现时,您的视图模型仅存在于服务器上。一旦响应发送到浏览器,您的班级就不再存在。
If you want to pass some data from client to server you have to:
如果您想将一些数据从客户端传递到服务器,您必须:
- post a form, or
- make an AJAX call
- 发布表格,或
- 进行 AJAX 调用
Take a look at jQuery ajaxmethod.
看看jQuery ajax方法。
ViewModel is used to pass data from controller to view so the view can render HTML. After the HTML is rendered ViewModel is discarded. There is no point is setting ViewModel properties in the view as nothing will use them later on.
ViewModel 用于将数据从控制器传递到视图,以便视图可以呈现 HTML。在 HTML 呈现后 ViewModel 被丢弃。在视图中设置 ViewModel 属性毫无意义,因为以后不会使用它们。
I believe you're coming from WebForms (UpdatePanel) background. The MVC is a totaly differentconcept/architecture. It works in a different way then WebForms / UpdatePanel.
我相信您来自 WebForms (UpdatePanel) 背景。MVC 是一个完全不同的概念/架构。它的工作方式与 WebForms / UpdatePanel 不同。