Setting property on the model object?



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 :

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?


11/22/2016 9:23:04 AM

Accepted Answer

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.

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.

3/3/2011 2:17:22 PM

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

Take a look at jQuery ajax method.

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.

I believe you're coming from WebForms (UpdatePanel) background. The MVC is a totaly different concept/architecture. It works in a different way then WebForms / UpdatePanel.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]