Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting property on the model object?

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 :

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?

BestRegards

like image 494
Banshee Avatar asked Mar 03 '11 13:03

Banshee


2 Answers

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.

like image 149
Darin Dimitrov Avatar answered Sep 18 '22 06:09

Darin Dimitrov


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.

like image 21
Jakub Konecki Avatar answered Sep 20 '22 06:09

Jakub Konecki