Updating a Razor Model from Javascript
How can I push the updated data to the @Model from javascript?
You absolutely cannot modify anything on the server from javascript. All you can do is an AJAX request to the server which will return refreshed data to the client. Remember that once the view is initially rendered there's no longer any notion of @Model
on the client. So talking about updating something that doesn't exist hardly makes any sense. After your AJAX request succeeds simply update the corresponding portions of your DOM that need to be updated. The controller action that you are hitting with AJAX could return all the necessary information for that.
RobVious
Updated on June 04, 2022Comments
-
RobVious almost 2 years
Here's the situation: I have a Razor-generated list of items (that needs to stay Razor-generated):
@model MG.ViewModels.Profile.ProfileDetailsViewModel foreach (var interest in Model.Interests) { <span class="subject-title">@interest.SubjectName</span> <a data-bind='click: function(){viewDescription(@Html.Raw(Json.Encode(interest)))}'class="subject-description-button" href="#" title="View Details">details</a> }
Users can update the details of each item by clicking a 'Details' link that encodes the Model for the
viewDescription
javascript function:self.viewDescription = function (data) { // pull data into KO observables self.selectedInterestDescription(data.Description); self.selectedInterestSubject(data.SubjectName); self.selectedInterestId(data.InterestId); self.triggerModal(true); };
Within the modal that gets triggered, the user can send an AJAX request to an endpoint that updates the description. This much is working as I'd expect.
What I'm struggling with is - when the user is done updating, the razor
Model
still has the old data. So when the user clicks 'details' from the Razor-generated list after updating, the old@model
data is encoded. How can I push the updated data to the@Model
from javascript?