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();
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
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
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With