2014-02-22 11 views
-2

我有一個複雜的模型如何最好Asp.Net MVC檢索一個複雜的視圖數據

public class Person 
{ 
    public int Id{get;set;} 
    public string Name{get; set;} 
    public virtual Address Address { get; set; } 
} 

public class Address 
{ 
    public int Id{get; set;} 
    public string State{get; set;} 
} 

在我的編輯視圖我顯示Address.State

@Html.EditorFor(model => model.Address.State) 

我的崗位操作方法看起來像

public ActionResult Edit(Person person) 
{ 
    var state = person.Address.State; 
    return view(); 
} 

但地址是null

使用這種複雜模型的正確方法是什麼?

+0

什麼'Contact'看起來像什麼? –

+1

您正在使用聯繫人模式,但在此處顯示人員模型! – ssilas777

+0

我同意@ ssilas777 –

回答

3

這裏有雲的解決方案 -

我用你的模型 -

public class Person 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual Address Address { get; set; } 
} 

public class Address 
{ 
    public int Id { get; set; } 
    public string State { get; set; } 
} 

則控制器動作這使得編輯觀點如下 -

public ActionResult Index() 
    { 
     Person p = new Person(); 
     p.Name = "Rami"; 
     p.Address = new Address(); 
     p.Address.State = "California"; 
     return View(p); 
    } 

而且編輯觀點如下 -

@model MVC.Controllers.Person 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

@using (Html.BeginForm("Submit","Person",FormMethod.Post)) 
{ 
    @Html.AntiForgeryToken() 

    @Html.ValidationSummary(true) 
    @Html.HiddenFor(model => model.Id) 

    @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" }) 
    @Html.EditorFor(model => model.Name) 
    @Html.ValidationMessageFor(model => model.Name) 

    @Html.LabelFor(model => model.Address.State, new { @class = "control-label col-md-2" }) 
    @Html.EditorFor(model => model.Address.State) 
    @Html.ValidationMessageFor(model => model.Address.State) 

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

最後,當你點擊提交按鈕,它會打到下面的控制器操作 -

public ActionResult Submit(Person p) 
    { 
     // Do something with Person p 
     return null; 
    } 

就是當你把一個斷點,你會得到新的值,如像下面 -

enter image description here

相關問題