2012-12-02 21 views
0

有人能告訴我如何在使用部分視圖時讓MVC綁定到視圖模型中的視圖模型?爲什麼MVC在使用部分視圖時不綁定?

public class HomeController : Controller 
    { 
     // 
     // GET: /Home/ 

     [HttpGet] 
     public ActionResult Index() 
     { 
      AVm a = new AVm(); 
      BVm b = new BVm(); 
      a.BVm = b; 

      return View(a); 
     } 

     [HttpPost] 
     public ActionResult Index(AVm vm) 
     { 
      string name = vm.BVm.Name; // will crash BVm == null 


      return View(vm); 
     } 
    } 

//索引視圖

@model MvcApplication4.Models.AVm 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

@using (Html.BeginForm("Index","Home",FormMethod.Post)) 
{ 
    <text>Id:</text> @Html.TextBoxFor(x => x.Id) 
    @Html.Partial("SharedView", Model.BVm) 

    <input type="submit" value="submit" /> 
} 

// SharedView

@model MvcApplication4.Models.BVm 

<text>Name:</text> @Html.TextBoxFor(x => x.Name) 



Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 

Source Error: 


Line 26:   public ActionResult Index(AVm vm) 
Line 27:   { 
Line 28:    string name = vm.BVm.Name; // will crash BVm == null 
Line 29: 
Line 30: 
+0

您可以先修復您的語法,因爲您的Action方法沒有方法名稱。另外看來,這個非命名方法是一個get請求,所以它將全部爲空。您需要顯示所有相關的Action方法和您的部分視圖代碼。 – MVCKarl

+0

如何返回類型方法名稱後?當你使用Test1模型時,爲了得到'Name'不應該使用vm.Test2.Name? –

+0

確定已更新。現在應該都有意義。 – chobo2

回答

1

的問題是,在你的局部模型BVm不知道它在視圖模型AVm屬性。所以,當你這樣做@Html.TextBoxFor(x => x.Name)它只會產生類似

<input type="text" name="Name" id="Name" value="" /> 

當你真正需要的是像

<input type="text" name="BVm.Name" id="Name" value="" /> 

您既可以生成自己喜歡這裏提出的輸入,或者你可以嘗試例如:

public ActionResult Index(AVm vm, BVm bvm) 

假設沒有衝突的屬性名稱。

+0

你的意思是把鏈接放在某個地方,或者你指的是其他人的帖子? 「...像這裏所建議的」。奇怪的是我很確定我在其他項目中做了這個,並且它工作。我將不得不考慮它。有點吸這個不行。 – chobo2

相關問題