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

后端 未结 3 1938
野性不改
野性不改 2020-12-25 10:44

I want to update model value in JavaScript as below but it is not working.

function updatePostID(val)
{
    @Model.addcomment.PostID = val;
}
3条回答
  •  长情又很酷
    2020-12-25 10:51

    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++)
    {
        
    Posted by : @Model.Post[i].Username
    @Model.Post[i].Content
    if(Model.loginuser == Model.username) { @Html.HiddenFor(model => model.Post[i].PostID) @Html.TextAreaFor(model => model.addcomment.Content) } }

提交回复
热议问题