2017-02-07 6 views
-1

で別のviewmodelsを渡す:私は以下のコードの一部を使用してPartialViewを使用して複数のビュー間でフォームを共有しようとしていますpartialview

これは私が

部分ビューを実装するすべてのビュー間で共有したいモデルです
namespace CSharp.Models.ViewModels 
{ 
    public class HomeViewModel 
    { 
     public string County { get; set; } 
     public ElectionType? Type { get; set; } 
    } 
} 

部分ビューファイルは、次のようになります。

部分ビューを実装するために必要なファイルの一つで
@model CSharp.Models.ViewModels.HomeViewModel 
@Html.TextBoxFor(model => model.County, new { @class = "form-control" })  
@Html.EnumDropDownListFor(model => model.Type, null, new { @class = "form-control"}) 

、私は次のコードを持っている:

Home View 

@model CSharp.Models.ViewModels.HomeViewModel 
@using (Html.BeginForm("Index", "Result", new { ViewBag.ReturnUrl }, FormMethod.Get, new { role = "form" })) 
{ 
    @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
    @Html.Partial("~/Views/Shared/_PartialViewFile.cshtml", Model) 
} 

私がページを実行するとき、それは必要なように動作します。

部分図を必要と一つの他のページは、私がViewModelに

Manage View 
@model CSharp.Models.ViewModels.HomeManageViewModel 
<form > 
    @Html.Partial("~/Views/Shared/_PartialViewFile.cshtml", Model.HomeViewModel); 
</form> 

HomeManageViewModelを使用しています。このビューは、私がManage Viewを実行すると、私はこのエラーを取得するこの

public class HomeManageViewModel 
{ 
    public HomeViewModel HomeViewModel { get; set; } 
    public IndexViewModel ManageViewModel { get; set; } 
} 

のように見えるがあります。

The model item passed into the dictionary is of type 'HomeManageViewModel', but this dictionary requires a model item of type 'HomeViewModel'

私は実際に0を渡しているのでin Manage View部分的に見ると、となります。

ビューモデル変数を部分ビューに渡すにはどうすればよいですか?

+0

レンダリングされた部分図を使用'Manage View'は' HomeManageViewModel'の代わりに 'HomeViewModel'を使います。代わりに 'HomeManageViewModel'にバインドされた' Manage View'ビューの部分ビューを個別に作成することができます。そのため、部分ビューモデルは親ビューページモデルに従う必要があります。 –

+0

サイドノート:エラーメッセージ(https://www.bing.com/search?q=c%23+The+model+item+passed+into+the+dictionary+is+&hl=ja)を検索することをおすすめします。 +型+しかし+この+辞書+は+型+ +型の+ item +を必要とします)、これはStephen Mueckeの素敵な答えと同じ説明を与えました。 –

答えて

3

それはHomeManageViewModel内のプロパティHomeViewModelの値がnullであることを意味します - あなたはそのnullので、ビューにモデルを渡す前に、GETメソッドでそれを初期化しませんでした。モデルがnullの場合、Partial()メソッドは、メインビューで宣言されたモデルを渡します。

GETメソッドでHomeManageViewModelとそのHomeViewModelを初期化し、ビュー

var model = new HomeManageViewModel() 
{ 
    HomeViewModel = new HomeViewModel(){ .... } 
} 
return View(model); 

またはビュー内にモデルを渡すのどちらか、あなたは、しかし

@Html.Partial("_PartialViewFile", new HomeViewModel()); 

注意を使用することができ、あなたのコードいますHtml.Partial()はモデルバインディングの正しい名前接頭辞を生成しないため、フォームでは機能しません。代わりにEditorTemplateを使用します。 HomeViewModel.cshtmlに部分の名前を変更する - クラスの名前と一致するように、とViews/Shared/EditorTemplatesフォルダ(またはViews/yourControllerName/EditorTemplatesフォルダ)に置き、その後、メインビューで、

@Html.EditorFor(m => m.HomeViewModel) 
関連する問題