使用 jQuery 为模型设置一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8520789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
set a value to model using jQuery
提问by ParPar
How can I set a value to my model using jQuery?
如何使用 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.
我有一个输入字段(它的 id="comment"),我希望@Model.Comment
使用 jQuery将其中的文本插入。
something like: @Model.Comment = $("#comment").val();
就像是: @Model.Comment = $("#comment").val();
采纳答案by Darin Dimitrov
How can I set a value to my model using 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.
这没有任何意义。jQuery 在客户端上运行。模型存在于服务器上。所以当 jQuery 在客户端执行时,服务器端代码和模型早就死了。
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 请求,将输入字段的值传递给它,以便服务器可以采取相应的操作并更新模型:
$.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:
在服务器上的哪个位置,您将有一个将被调用的 Foo 控制器操作:
[HttpPost]
public ActionResult Foo(string comment)
{
// TODO: do something with the value of the comment and return a result
// to the client
...
}
回答by DevDave
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.
我绝不会不同意 Darin(他在这里回答了我一半的问题!)但会提出来以防 OP 或其他任何人认为它有用。
By giving an Html attribute to a model value:
通过为模型值提供 Html 属性:
@Html.HiddenFor(x => x.Object.Id, new { id = "Id" } )
You can then set the value with Jquery like so
然后您可以像这样使用 Jquery 设置值
$("#Id").val(5); // or whatever value