简体   繁体   English

在模型对象上设置属性?

[英]Setting property on the model object?

Hi, 嗨,

I am building a ASP.NET MVC site and have runned across a problem. 我正在构建一个ASP.NET MVC站点,并遇到了一个问题。 In my project I got a modelview class that contains a couple of properties, for example : 在我的项目中,我得到了一个包含几个属性的modelview类,例如:

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. 这个modelview类绑定到一个类型化的视图,我需要能够设置属性。 How do I do this with javascript/jquery? 我如何使用javascript / jquery执行此操作? I have tried with Model.MyProperty1 = 1, but that does not work? 我尝试使用Model.MyProperty1 = 1,但这不起作用?

BestRegards 最好的祝福

You cannot set server side values with javascript. 您无法使用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. 您可以使用HTML帮助器将这些值绑定到输入字段(文本框,隐藏字段,textareas,下拉列表...),然后使用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. 然后,当将包含的表单提交给服务器时,新值将绑定到您的视图模型。

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 ajax method. 看看jQuery ajax方法。

ViewModel is used to pass data from controller to view so the view can render HTML. ViewModel用于将数据从控制器传递到视图,因此视图可以呈现HTML。 After the HTML is rendered ViewModel is discarded. HTML呈现后,ViewModel将被丢弃。 There is no point is setting ViewModel properties in the view as nothing will use them later on. 在视图中设置ViewModel属性没有意义,因为稍后什么都不会使用它们。

I believe you're coming from WebForms (UpdatePanel) background. 我相信你来自WebForms(UpdatePanel)背景。 The MVC is a totaly different concept/architecture. MVC是一个完全不同的概念/架构。 It works in a different way then WebForms / UpdatePanel. 它的工作方式与WebForms / UpdatePanel不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM