asp.net-mvc 如何在 Razor 视图中更新 JavaScript 中的模型值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16174465/
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
How do I update a model value in JavaScript in a Razor view?
提问by michaeld
I want to update model value in JavaScript as below but it is not working.
我想更新 JavaScript 中的模型值,如下所示,但它不起作用。
function updatePostID(val)
{
@Model.addcomment.PostID = val;
}
in Razor view as shown below
在 Razor 视图中,如下所示
foreach(var post in Model.Post)
{
<br/>
<b>Posted by :</b> @post.Username <br/>
<span>@post.Content</span> <br/>
if(Model.loginuser == Model.username)
{
@Html.TextAreaFor(model => model.addcomment.Content)
<button type="submit" onclick="updatePostID('@post.PostID');">Add Comment </button>
}
}
Can anyone tell me how to assign model value in JavaScript?
谁能告诉我如何在 JavaScript 中分配模型值?
回答by codingbiz
This should work
这应该工作
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
然后有一个隐藏字段或其他控件 PostID
@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)
回答by Jason Berkan
The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.
模型 ( @Model) 仅在构建页面时存在。一旦页面在浏览器中呈现,所有存在的就是 HTML、JavaScript 和 CSS。
What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenForwill suffice.
您要做的是将 PostID 放在隐藏字段中。由于 PostID 值是固定的,实际上不需要 JavaScript。一个简单的@HtmlHiddenFor就足够了。
However, you will want to change your foreach loop to a for loop. The final solution will look something like this:
但是,您需要将foreach 循环更改为 for 循环。最终的解决方案将如下所示:
for (int i = 0 ; i < Model.Post; i++)
{
<br/>
<b>Posted by :</b> @Model.Post[i].Username <br/>
<span>@Model.Post[i].Content</span> <br/>
if(Model.loginuser == Model.username)
{
@Html.HiddenFor(model => model.Post[i].PostID)
@Html.TextAreaFor(model => model.addcomment.Content)
<button type="submit">Add Comment</button>
}
}
回答by Dan Esparza
You could use jQuery and an Ajax callto post the specific update back to your server with Javascript.
您可以使用jQuery 和 Ajax 调用通过 Javascript 将特定更新发布回您的服务器。
It would look something like this:
它看起来像这样:
function updatePostID(val, comment)
{
var args = {};
args.PostID = val;
args.Comment = comment;
$.ajax({
type: "POST",
url: controllerActionMethodUrlHere,
contentType: "application/json; charset=utf-8",
data: args,
dataType: "json",
success: function(msg)
{
// Something afterwards here
}
});
}

