如何将存储过程的列表结果传递到ASP.NET MVC视图?

时间:2014-01-22 11:05:26

标签: asp.net-mvc stored-procedures

您好,我有以下存储过程:

    ALTER PROCEDURE [dbo].[uspApp_SelectListAutomation]

           @id int,
          @UserID int

            AS
          BEGIN
  SET NOCOUNT ON;

SELECT Automation_notes, Automation_recepientEmail, Automation_frequency
FROM Appmarket_AutomatedReports
WHERE UserID = @UserID AND id = @id
END

我在我的索引操作中调用这个strored过程,如下所示:

    var listautomation = orderdata.uspApp_SelectListAutomation(id, userid).ToList();
     ViewData["listresults"] = listautomation;

现在我需要将其传递到我的视图中,并且必须显示 Automation_notes Automation_recepientEmail Automation_frequency

下面是我写的静态代码:

 <li style="border-left: 2px solid red;"><a href="Index/1">
            <div class="col-14">
                   <h5>
                   **Automation Notes**
                       </h5>
                 <div class="stats">
        ( RECIPIENT: **Automation_recepientEmail** | EVERY **Automation_frequency** | EXPIRES: 19 January 2025 )
                       </div>
                    </div>
                   <div class="clear">
                  </div>
                  </a></li>

有人可以告诉我如何通过从存储过程中获取结果并将其传递给我的视图来使其动态化?

2 个答案:

答案 0 :(得分:1)

你的模型和ViewModel应该是 -

public class ViewModel
{
    public List<DataModel> Items { get; set; }
}

public class DataModel
{
    public string Automation_notes { get; set; }
    public string Automation_recepientEmail { get; set; }
    public string Automation_frequency { get; set; }
}

你的控制器应该是 -

public ActionResult Index()
{
    // Here you need to get data from SQL and populate the properties accordingly, I mean you need to 
    // call buisness layer method here
    ViewModel model = new ViewModel();
    model.Items = new List<DataModel>();
    model.Items.Add(new DataModel() { Automation_notes = "Note1", Automation_frequency = "10", Automation_recepientEmail = "Eamil1" });
    model.Items.Add(new DataModel() { Automation_notes = "Note2", Automation_frequency = "20", Automation_recepientEmail = "Eamil2" });

    return View(model);
}

您应该查看 -

@model MVC.Controllers.ViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<table class="table">
    <tr>
        <th></th>
    </tr>

@foreach (var item in Model.Items) {
    <tr>
        <td>
            @Html.Label(item.Automation_frequency)
        </td>
        <td>
            @Html.Label(item.Automation_notes)
        </td>
        <td>
            @Html.Label(item.Automation_recepientEmail)
        </td>
    </tr>
}

</table>

输出 - enter image description here

答案 1 :(得分:0)

首先从控制器传递viewmodel,如此

public ActionResult ActionName()
        {
            //your code
           return View(listautomation);               
        }

然后将其绑定在您的视图部分中

@model ViewModel.ListAutomation

像这样获取值

<input type="text" id="id" value="@Model.ListAutomation " readonly="True"/>