简体   繁体   English

ASP.NET 5 MVC 6控制器以查看数据访问

[英]ASP.NET 5 MVC 6 Controllers to View data access

I am new to ASP.NET and learning as I go by doing some personal projects. 我是ASP.NET的新手,并通过做一些个人项目来学习。

So my question is how to access data that is passed from controller to the view? 所以我的问题是如何访问从控制器传递到视图的数据?

Here is my controller code: 这是我的控制器代码:

        [HttpPost]
        public IActionResult Index(PowerShellCmd script)
        {
            PowerShellModule execute = new PowerShellModule();
            var results = execute.ExecuteCode(script);
            StringBuilder builder = new StringBuilder();
            foreach (var psObject in results)
            {
                // Convert the Base Object to a string and append it to the string builder.
                // Add \r\n for line breaks
                builder.AppendLine(psObject.BaseObject.ToString());
            }
            var data = builder.ToString();
            return View(data); // Transfer data to view
        }

In the return view above I am providing a variable that I want to access in the view. 在上面的返回视图中,我提供了要在视图中访问的变量。 So in view I used below code with @Model to access the data in front end. 因此,在视图中,我将下面的代码与@Model一起使用来访问前端的数据。 I am not sure if that is the right way, but any suggestion is appreciated. 我不确定这是否是正确的方法,但是任何建议都会受到赞赏。 :) :)

<textarea asp-for="CmdOutput" style="width:700px; height:200px;">
    @Model
</textarea>

Model 模型

    public class MyModel
    {
        public string Data { get; set; }
    }

Controller 控制者

    [HttpPost]
    public IActionResult Index(PowerShellCmd script)
    {
        PowerShellModule execute = new PowerShellModule();
        var results = execute.ExecuteCode(script);
        StringBuilder builder = new StringBuilder();
        foreach (var psObject in results)
        {
            // Convert the Base Object to a string and append it to the string builder.
            // Add \r\n for line breaks
            builder.AppendLine(psObject.BaseObject.ToString());
        }
        MyModel myModel = new MyModel();
        myModel.Data = builder.ToString();
        return View(myModel); // Transfer data to view
    }

View 视图

@model MyModel

<div>
@MyModel.Data
</div>

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

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