使用jQuery为model建立一个值

时间:2011-12-15 13:23:18

标签: jquery asp.net-mvc-3 model

如何使用jQuery为我的模型设置值?

我有一个输入字段(其id =“comment”),我想将其中的文本插入@Model.Comment 使用jQuery。

类似于:@Model.Comment = $("#comment").val();

2 个答案:

答案 0 :(得分:39)

我不同意达林(他在这里回答了我的一半问题!)但是如果OP或其他任何人发现它有用的话,我会提出这个问题。

通过为模型值提供Html属性:

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

然后可以使用Jquery设置值,如此

$("#Id").val(5); // or whatever value

答案 1 :(得分:3)

  

如何使用jQuery为我的模型设置值?

这没有任何意义。 jQuery在客户端上运行。该模型存在于服务器上。因此,当jQuery在客户端上执行时,服务器端代码和模型已经很久了。

您可以从客户端执行的操作是向服务器发送AJAX请求,并向其传递输入字段的值,以便服务器可以采取相应的操作并更新模型:

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

在服务器上,您将有一个将被调用的Foo控制器操作:

[HttpPost]
public ActionResult Foo(string comment)
{
    // TODO: do something with the value of the comment and return a result
    // to the client
    ...
}