How do I update a model value in JavaScript in a Razor view? How do I update a model value in JavaScript in a Razor view? javascript javascript

How do I update a model value in JavaScript in a Razor view?


This should work

function updatePostID(val){    document.getElementById('PostID').value = val;    //and probably call document.forms[0].submit();}

Then have a hidden field or other control for the PostID

@Html.Hidden("PostID", Model.addcomment.PostID)//OR@Html.HiddenFor(model => model.addcomment.PostID)


The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++){    <br/>    <b>Posted by :</b> @Model.Post[i].Username <br/>    <span>@Model.Post[i].Content</span> <br/>    if(Model.loginuser == Model.username)    {        @Html.HiddenFor(model => model.Post[i].PostID)        @Html.TextAreaFor(model => model.addcomment.Content)        <button type="submit">Add Comment</button>    }}


You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.

It would look something like this:

function updatePostID(val, comment){    var args = {};    args.PostID = val;    args.Comment = comment;    $.ajax({     type: "POST",     url: controllerActionMethodUrlHere,     contentType: "application/json; charset=utf-8",     data: args,     dataType: "json",     success: function(msg)      {        // Something afterwards here     }    });}