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

后端 未结 3 1929
野性不改
野性不改 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++)
    {
        <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>
        }
    }
    
    0 讨论(0)
  • 2020-12-25 11:06

    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
    
         }
        });
    
    }
    
    0 讨论(0)
  • 2020-12-25 11:09

    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)
    
    0 讨论(0)
提交回复
热议问题