set a value to model using jQuery

前端 未结 2 1918
南方客
南方客 2021-02-02 17:46

How can I set a value to my model using jQuery?

I have an input field (which its id=\"comment\") and I want the text in it to be inserted into @Model.Comment

相关标签:
2条回答
  • 2021-02-02 18:41

    How can I set a value to my model using jQuery?

    This doesn't make any sense. jQuery runs on the client. The Model lives on the server. So by the time jQuery executes on the client, the server side code and the Model is long dead.

    What you could do from the client is send an AJAX request to the server passing it the value of the input field so that the server can take respective actions and update the model:

    $.ajax({
        url: '@Url.Action("foo")',
        type: 'POST',
        data: { comment: $("#comment").val() },
        function(result) {
            // TODO: process the server results
        }
    });
    

    Where on the server you will have a Foo controller action that will be invoked:

    [HttpPost]
    public ActionResult Foo(string comment)
    {
        // TODO: do something with the value of the comment and return a result
        // to the client
        ...
    } 
    
    0 讨论(0)
  • 2021-02-02 18:47

    Far be it from me to disagree with Darin (he's answered half my questions on here!) but will put this up in case the OP or anyone else finds it useful.

    By giving an Html attribute to a model value:

    @Html.HiddenFor(x => x.Object.Id, new { id = "Id" } )
    

    You can then set the value with Jquery like so

    $("#Id").val(5); // or whatever value
    
    0 讨论(0)
提交回复
热议问题