我无法从db中获取storedprocedure结果并在视图中显示。在DB Storedprocedure工作正常
我在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
我正在执行StoredProcedure的控制器代码
我尝试使用以下代码但面对但看不到ViewBag中的数据它在ViewBag上的Foreach循环上给出错误,即BusinessLogo列不存在,但您可以在sp中看到我正在获取BusinessLogo以及其他列的类似错误< / p>
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获取的数据传递给视图?
答案 0 :(得分:0)
做类似的事情,这不是确切的解决方案,但是沿着这条路走。 1)定义您的Viemodel以存储StoredProc中的数据。
AddressModel.cs
<<extend>>
AddressSearchResultModel.cs
public class AddressModel
{
public string City {get; set;}
public string State {get; set;}
}
2)从storedproc获取数据后,将数据传递给定义的模型。
public class AddressSearchResultModel
{
public List<AddressModel> AddressResults {get; set;}
}
3)最后从viewmodel
渲染视图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);
}