Setting properties of a model object?

Hi,

I am creating an ASP.NET MVC site and have encountered a problem. In my project, I got a modelview class that contains a couple of properties, for example:

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 properties. How to do this using javascript / jquery? I tried with Model.MyProperty1 = 1, but this does not work?

Best regards

+8
javascript jquery asp.net-mvc
source share
2 answers

You cannot set values ​​on server side using javascript. You can bind these values ​​to input fields (text fields, hidden fields, text fields, drop-down lists, ...) using HTML helpers, and then using javascript you can change the values ​​of these input fields.

So, for example, if you have a hidden field:

 <input type="hidden" name="foo" id="foo" value="bar" /> 

You can change its value as follows:

 $('#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.

+22
source share

You are trying to set a server side property - this will not work. Your view model only exists on the server when rendering your view. Once the response is sent to the browser, your class no longer exists.

If you want to transfer some data from the client to the server, you must:

  • send form or
  • make an ajax call

Check out the jQuery ajax method .

ViewModel is used to transfer data from the controller for viewing, so that the view can display HTML. After rendering, the HTML ViewModel is discarded. It makes no sense to configure the ViewModel properties in the view, since it will not use them in the future.

I suppose you came from the background of WebForms (UpdatePanel). MVC is a completely different concept / architecture. It works differently than WebForms / UpdatePanel.

+2
source share

All Articles