如何在MVC视图中显示存储过程的结果

3

我无法从数据库中获取存储过程的结果并在视图中显示。在数据库中,存储过程运行良好。

我的MsSQL存储过程

ALTER PROCEDURE [dbo].[Search]
    (
    @param1 varchar(max), 
    @param2 varchar(max),
    @param3 varchar(max),
    @param4 varchar(max)
    )
AS
BEGIN
select BusinessLogo,BusinessTitle,Details,ProfileUrl,Location,Country from ClientBusinesses where location like '%'+@param1+'%' and location like '%'+@param2+'%'
 and location like '%'+@param3+'%' and location like '%'+@param4+'%'
END

我执行存储过程的控制器代码

我尝试使用以下代码,但在ViewBag中无法看到数据。在ViewBag上使用foreach循环时出现错误,错误信息为“列BusinessLogo不存在”,但是在存储过程中可以看到我正在获取BusinessLogo列,其他列也有类似的错误。

ViewBag listdata = db.Search(Country, state, city, str);

我也尝试了以下代码 -
 List<ClientBusiness> listd=new List<ClientBusiness>();
 listd=db.Search(Country, state, city, str);

但它会报错。
Error   2   Cannot implicitly convert type 'System.Data.Entity.Core.Objects.ObjectResult<string>' to 'System.Collections.Generic.List<PromoteMyName.ClientBusiness>'    F:\Desktop DATA\Desktop 23 Feb\PromoteMyName\PromoteMyName\Controllers\HomeController.cs    135 23  PromoteMyName

我在视图中使用以下简单代码

@foreach(var item in  ViewBag.listdata)
   {
}

这是通过ViewBag将从SP获取的数据传递到视图可能吗?

1
你需要将数据投影到一个模型中,并将该模型的集合传递给视图。 - user3559349
@StephenMuecke 你是指ViewModel吗? - user5493185
我正在使用数据库优先的方法。ClientBusiness是我的表。如果我在存储过程中使用Select *,我能将clientbusiness模型传递给视图吗? - user5493185
是的,在视图中创建一个视图模型,其中包含您想要在视图中显示的属性,并将该模型的集合传递给视图。 - user3559349
@Nathan - 我认为不是。请参考这个关于SQL注入和存储过程的MSDN链接:存储过程是否能够防止SQL注入。Steve并没有创建一个新的字符串来执行,而是将%附加到参数上,这应该是可以的。 - Igor
显示剩余6条评论
1个回答

0

做类似于这样的事情,这不是确切的解决方案,但沿着这条路线走。 1)定义您的ViewModel以存储来自StoredProc的数据。

AddressModel.cs

public class AddressModel
{
    public string City {get; set;}
    public string State {get; set;}
}

AddressSearchResultModel.cs

public class AddressSearchResultModel
{
    public List<AddressModel> AddressResults {get; set;}
}

2) 一旦您从存储过程中获取数据,将数据传递给定义的模型。

var dataFromStoredProc=db.Search(Country, state, city, str);
// Translate the addressSerachResultModel to addressSearchResultModel
var addressSearchResultModel= new AddressSearchResultModel();
var addressModel= new AddressModel()
foreach(var item in dataFromStoredProc )
{
    //Assign every property from the dataFromStoredProc to     AddressModel
    //and add it to the list
    addressSearchResultModel.Add(AddressModel);
}

3) 最后从您的视图模型呈现视图

[HttpGet]
public ActionResult GetResults()
{
    var dataFromStoredProc=db.Search(Country, state, city, str);

    // Translate the addressSerachResultModel to AddressSearchResultModel
    var addressSearchResultModel= new AddressSearchResultModel();
    var addressModel= new AddressModel()
    foreach(var item in dataFromStoredProc )
    {
        //Assing every property from the dataFromStoredProc to AddressModel
        //and add it to the list
        addressSearchResultModel.Add(AddressModel);
    }

    return View(addressSearchResultModel);       
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接