I want to update model value in JavaScript as below but it is not working.
function updatePostID(val)
{
@Model.addcomment.PostID = val;
}
in Razor view as shown below
foreach(var post in Model.Post)
{
<br/>
<b>Posted by :</b> @post.Username <br/>
<span>@post.Content</span> <br/>
if(Model.loginuser == Model.username)
{
@Html.TextAreaFor(model => model.addcomment.Content)
<button type="submit" onclick="updatePostID('@post.PostID');">Add Comment </button>
}
}
Can anyone tell me how to assign model value in JavaScript?
This should work
Then have a hidden field or other control for the
PostID
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:
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: