3

I'm using ASP.NET MVC 3. I have a question if it's possible to update the model, even if it's not being sent to the controller? Perhaps the question is completle of, or I'm doing things in a wrong way?

I have an ajax-call to a controller method. I'm passing in an id. I would like the controller to find some stuff in the db, and then update the model, passing it back to the view.

I've got a pretty big model... I've found some solutions, where to convert the model to a javascript object, and send it to the controller. Is that the only/right way?

How to send a model in jQuery $.ajax() post request to MVC controller method

I thought that maybe the controller has the model, where I could update some fields in it?

The call to the controller:

    function getBis(id) {
        $.ajax({
            type: "GET",
            url: '@Url.Action("GetBis")',
            data: { "id": id },
            dataType: 'json',
            cache: false,
            success: function (data) {
                // Do something here
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("Problem!");
            }
        });
    }

The controller code:

    public ActionResult GetBis(string id)
    {
        BeslutIStortDTO viewModel = new BeslutIStortDTO();

        int theId;
        if (!Int32.TryParse(id, out theId))
            throw new Exception("Wrong id");

        viewModel = _blLayer.GetBIS(theId);

        // somehow update the model here!

        return View("index", viewModel);
    }
Community
  • 1
  • 1
kaze
  • 4,299
  • 12
  • 53
  • 74
  • What are you trying to do? What model do you want to update? The model that was used to render the view is long gone by the time you trigger the AJAX request. – Darin Dimitrov May 02 '12 at 09:19
  • That was what I was afraid of. I would like to add additional stuff to my model, the one that was used to render the view in the first place. – kaze May 02 '12 at 09:33
  • this model no longer exists. You could query your database to update it directly there. – Darin Dimitrov May 02 '12 at 09:48
  • how are you planing to use the model once you return it? are you going to update the view with HTML, are you going to manipulate the returned data with javascript? – Bob The Janitor May 03 '12 at 20:09

3 Answers3

0

usually you "pass the model" between JQuery and your controller when you need to "reflect" what ever is changed on your UI without doing any mapping(MVC is smart enough to construct a new object from the parameters you give it). In your case you said you just need to pass an ID to do some stuff on your model. So all you need to do is pass the ID as parameter, get it within the controller action and then do your stuff.

have a look at the below link

Pass a parameter to a controller using jquery ajax

Community
  • 1
  • 1
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
  • I'm using the id to get stuff, that I want to send back to the view. Adding additional data to the model. – kaze May 02 '12 at 09:30
0

First by updating the model, do you mean you want to update the record in the DB? That is not a good practice to do in a get request. If not read on..

Once you got your object with GetBis method, you can change all properties of it.

If you want to send this object to Javascript, use JSON Result.

return JSON(viewModel);

and one more thing, don't initialize view model in the first line of code, unnecessary object allocation.

Kartheek N
  • 211
  • 1
  • 8
0

The short answer is Yes and No, depending upon exactly what you mean, however you may want to reconsider your design. I would guess you are actually trying to render a Domain Entity to your view, rather than a View Model. This is a common newbie mistake.

One thing I would like to clarify is the difference between domain entities, and view models.

Domain entities are generally pulled from your persistence layer, and that is where your state changes should take place.

View models are temporary constructs, created on the server, just before a view is output as HTML, to be used as the data storehouse for the View template. It does not exist on the client's web browser after the request, and it no longer lives on the server after a request.

If you are using Ajax to perform some type of data change, instead of reloading the page, then what you would generally do, is make changes to the Domain object (via Id), rather than the View Model you originally passed in (which doesn't exist anymore).

For example.

I have a domain entity which is tied to a database record. Person {long id=1;string name=bob;bool enabled=true}

I have a view model (that i map to bob in the initial get controller function) PersonData {long id=1;string name ="bob", enabled=true}

To do this, in my initial page GET controller function, i pull up the Domain entity bob from the database, copy his data over to an instance of the view model, then pass the view model to the View("EditPerson",pd) action result, which goes through the razor view page and view model, and substitutes values into the HTML it is writing to the response stream, where appropriate.

Now, you have HTML on a client's web browser, that is IT. No view model exists. Now you have some Ajax which is browser side scripting, that says when I click a "Toggle Status" link for instance, what would happen is the browser (without changing pages) will submit a request to the ajax url you provided, passing in an Id of bob. Your controller function should then load the Entity version of Bob, and toggle the Entity version of Bob's enabled to an appropriate value, then persist that change to the database.

Nowhere at all does the original VIEW Model come into play, as it has not existed since the initial page was rendered to the browser.

Is there something specific you want to accomplish that you cannot see a way to do with this pattern?

David C
  • 3,610
  • 3
  • 21
  • 23
  • I'm doing it pretty much like you describe, with view models. I'll describe my case a little more: In the first get (index), I populate "a lot" of data, in select-lists etc, with the viewModel. However, there are still more data to get, depending on what the user does after the first get. He then does something, I do an ajax call, and wants to "fill" more data to the viewModel (instead of getting it all again). This is (maybe) a special case where I want to fill the viewModel in (at least) two steps, depending on what the user does. I've solved it now, with pure javascript. – kaze May 04 '12 at 05:45