简体   繁体   English

JS总是返回一个空模型

[英]JS always returns an empty model

Model: 模型:

public class TestModel
{
    public string SomeString { get; set; }
}

View: 视图:

@model MyProject.ViewModels.TestModel

<script>
    function Test()
    {
        var modelDataJSON = '@Html.Raw(Json.Encode(Model))';
        alert(modelDataJSON);
    }
</script>

@{Model.SomeString = "asdf";}

<button type="button" onclick="Test()">Test</button>

JS alert always return JSON where all fields are set to null: {"SomeString:null} JS警报始终返回所有字段均设置为null的JSON:{“ SomeString:null}

That's normal behaviour...you should change the value before the script block like below... 这是正常现象...您应该在脚本块之前更改值,如下所示...

@{Model.SomeString = "asdf";}

<script>
    function Test()
    {
        var modelDataJSON = '@Html.Raw(Json.Encode(Model))';
        alert(modelDataJSON);
    }
</script>

What happens is that before the page is rendered, Razor will resolve all the "symbols and expressions" specified in the view, so, this line... 发生的情况是,在呈现页面之前,Razor将解析视图中指定的所有“符号和表达式”,因此,此行...

var modelDataJSON = '@Html.Raw(Json.Encode(Model))';

will be replaced with the actual value of the model before the page gets sent to the browser... 在页面发送到浏览器之前将被模型的实际值替换...

var modelDataJSON = '{"SomeString":null}';

However, if you change the value before the the script block Razor will replace the expression with the current value. 但是,如果在脚本块之前更改该值,Razor将用当前值替换该表达式。 You can easily see this by viewing the page source on your browser how the value gets replaced with a "hard-coded" string 通过在浏览器上查看页面源,您可以轻松地看到此内容,该值如何用“硬编码”字符串替换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM