[英]MVC - Can I set a model attribute in the view and get the value form a script?
This is the Controller that returns the above-mentioned view: 这是返回上述视图的Controller:
public PartialViewResult Day()
{
Day model = new Day();
return PartialView("_Day", model);
}
[HttpPost]
public PartialViewResult Day(Day model)
{
return PartialView("_Day", model);
}
I wrote both the Get and the Post method after I read this question. 阅读此问题后,我同时编写了Get和Post方法。 Note that I haven't set the model in the Controller. 请注意,我尚未在Controller中设置模型。
Then I have my View: 然后我有自己的看法:
@model Timing.Models.Day
@{
Timing.Models.Day d = new Timing.Models.Day();
d.UserId = "some value";
}
This piece of code is working fine: when I go to retrieve, or display, d.UserId
I get the right value. 这段代码运行良好:当我去检索或显示d.UserId
我得到了正确的值。
Furthermore I have a script in the same view. 此外,我在同一视图中有一个脚本。
<script>
function getUserId() {
//some code that gets a string
return userId;
}
</script>
And also this script is working right. 而且此脚本也可以正常工作。
I looked for a solution and this is the best I've been able to find: 我正在寻找解决方案,这是我所能找到的最好的解决方案:
@{
Timing.Models.Day d = new Timing.Models.Day();
d.UserId = Page.ClientScript.RegisterStartupScript(this.GetType(), "Getuser", "getUserId()", true);
}
But it's not working because of something that is null
(I wasn't able to understand what was null though). 但是由于某些null
而无法正常工作(尽管我无法理解什么是空值)。
Is there a way to solve this problem? 有办法解决这个问题吗?
For those who ask, I'm using a script because the value I want to set is the one of an html element (this is my related question). 对于那些问的人,我使用脚本是因为我要设置的值是html元素之一(这是我的相关问题)。
Thanks! 谢谢!
Declare your variable you want in javascript 在JavaScript中声明您想要的变量
@{
var useridForjs = model.property // access model and set useridForjs
}
to use in javascript 在javascript中使用
<script>
function getUserId() {
//some code that gets a string
var myserversidevarvalue = '@useridForjs'; // here myserversidevarvalue will store value..
return userId;
}
</script>
Make it easy on yourself and inject your id into a hidden form field, easily obtainable by javascript. 让自己轻松一点,并将您的ID注入到一个隐藏的表单字段中,可以很容易地通过javascript获取。 Add this to your view: 将此添加到您的视图:
Html.HiddenFor(model.userId)
Then access it like this: 然后像这样访问它:
function getUserId() {
return $('#userId').val();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.