Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set a value to model using jQuery

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();

like image 810
ParPar Avatar asked Dec 15 '11 13:12

ParPar


2 Answers

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
like image 100
DevDave Avatar answered Oct 06 '22 02:10

DevDave


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
    ...
} 
like image 26
Darin Dimitrov Avatar answered Oct 06 '22 04:10

Darin Dimitrov