3

dbからstoredprocedureの結果をフェッチできず、ビューに表示できません。 DBのStoredProcedureで私はコードに従うが直面しかし、内のデータを参照してくださいすることはできません使用してみましたのStoredProcedureMVCビューで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 '%'[email protected]+'%' and location like '%'[email protected]+'%' 
and location like '%'[email protected]+'%' and location like '%'[email protected]+'%' 
END 

コントローラコードでは細かい

私のStoredProcedureに取り組んでいます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); 

しかし、それは私が

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

下に簡単なコードを、この可能です使用していますビューでエラー

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 

を与えますspからフェッチしたデータをビューバッグ経由で渡す?

+1

からビューをレンダリングします。 –

+0

@StephenMuecke viewmodelを意味しますか –

+0

私はdbfirstアプローチを使用しています。 ClientBusinessは私のテーブルです。私がストアドプロシージャでSelect *を使用するとクライアントビジネスモーダルを渡すことができます –

答えて

0

このようなことをしてください。これは正確な解決策ではありませんが、この行に沿って行ってください。 1)StoredProcからのデータを保存するためのViemodelを定義します。

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)あなたがにStoredProcからデータを取得すると、定義されたモデルにデータを渡します。

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)最後に、あなたのviewmodelあなたがモデルにデータを投影し、ビューにそのモデルのコレクションを渡す必要が

[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);  
} 
関連する問題