set a value to model using jQuery

2019-03-13 06:00发布

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 using jQuery.

something like: @Model.Comment = $("#comment").val();

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-13 06:18

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
    ...
} 
查看更多
\"骚年 ilove
3楼-- · 2019-03-13 06:26

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
查看更多
登录 后发表回答