0

In my razor view, my model has one property composed only by a get.

@model Contoso.MvcApplication.ViewModels.QuizCompletedViewModel

<p>@Model.Property1</p>

By default, this property starts with the value: 10. And all the time has that value in view. I would like when I press clic on a img tag, this property can be updated (because all the time the value persisted), how can I update the property without refresh the page?

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
Darf Zon
  • 6,268
  • 20
  • 90
  • 149

1 Answers1

1

Step 1) Modify the view to make the counter addressable by jquery:

@model Contoso.MvcApplication.ViewModels.QuizCompletedViewModel

<p id="my-counter">@Model.Property1</p>

Now, do you need this incremented value on the server?

IF YOU DO NOT need this incremented value sent to the server:

Step 2) Increment the value on the client using javascript/jquery:

$("#my-image").click(function () { 
    var theValue = parseInt($("#my-counter").html());
    theValue = theValue + 10;
    $("#my-counter").html(theValue);
});

IF YOU DO NEED TO INCREMENT ON THE SERVER:

Step 2) Create a controller action to handle the increment

public ActionResult Increment(int currentValue)
{
    // save to the database, or do whatever
    int newValue = currentValue + 10;
    DatabaseAccessLayer.Save(newValue);

    Contoso.MvcApplication.ViewModels.QuizCompletedViewModel model = new Contoso.MvcApplication.ViewModels.QuizCompletedViewModel();

    model.Property1 = newValue;

    // If no exception, return the new value
    return PartialView(model);
} 

Step 3) Create a partial view which will return ONLY the new value

@model Contoso.MvcApplication.ViewModels.QuizCompletedViewModel

@Model.Property1

Step 4) Modify the jquery to post to this new action, which returns the new count, and displays it

$("#my-image").click(function () { 
    $.get('/MyController/Increment/' + $("#my-counter").html(), function(data) {
        $("#my-counter").html(data);
    });
});

Code is untested, but I think pretty close, and hopefully this gives the right idea.

J.T. Taylor
  • 4,147
  • 1
  • 23
  • 23