使用 jQuery 为模型设置一个值 [英] set a value to model using jQuery

查看:19
本文介绍了使用 jQuery 为模型设置一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有一个输入字段(其 id="comment"),我希望将其中的文本插入到 @Model.Comment使用 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.

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

推荐答案

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

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

这没有任何意义.jQuery 在客户端上运行.模型存在于服务器上.所以当 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.

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

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

您将在服务器上的哪个位置调用 Foo 控制器操作:

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
    ...
} 

这篇关于使用 jQuery 为模型设置一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆