2011-08-22 30 views
2

我創建了一個應用程序,允許我記錄食譜。我試圖創建一個視圖,允許我添加配方的基礎知識,例如食譜名稱,配方日期,在&使用的成分烹飪溫度。我的控制器viewmodel沒有填充我的動態視圖模型

我正在創建一個視圖,其中包含一些jquery加載部分視圖clientside。

後在即時通訊有幾個麻煩試圖從已使用jquery加載的部分視圖獲取值。

一個砍下我的主要觀點的版本看起來像(我最初想1個的局部視圖加載)

<div id="ingredients"> 
     @{ Html.RenderPartial("_AddIngredient", new IngredientViewModel()); } 
    </div> 
    <script type="text/javascript"> 
    $(document).ready(function() { 
    var dest = $("#ingredients"); 
    $("#add-ingredient").click(function() { 
     loadPartial(); 
    }); 
    function loadPartial() { 
     $.get("/Recipe/AddIngredient", {}, function (data) { $('#ingredients').append(data); }, "html"); 
    }; 
}); 
</script> 

我的部分觀點貌似

<div class="ingredient-name"> 
    @Html.LabelFor(x => Model.IngredientModel.IngredientName) 
    @Html.TextBoxFor(x => Model.IngredientModel.IngredientName) 
</div> 
<div class="ingredient-measurementamount"> 
    @Html.LabelFor(x => Model.MeasurementAmount) 
    @Html.TextBoxFor(x => Model.MeasurementAmount) 
</div> 
<div class="ingredient-measurementtype"> 
    @Html.LabelFor(x => Model.MeasurementType) 
    @Html.TextBoxFor(x => Model.MeasurementType) 
</div> 

控制器後

[HttpPost] 
    public ActionResult Create(RecipeViewModel vm,IEnumerable<string>IngredientName, IEnumerable<string> MeasurementAmount, IEnumerable<string> MeasurementType) 
    { 

最後,我的viewmodel看起來像

public class IngredientViewModel 
{ 
    public RecipeModel RecipeModel { get; set; } 
    public IEnumerable<IngredientModel> Ingredients { get; set; } 

} 

我的控制器是很醜陋......使用Inumerble以獲取MeasurementAmount & MeasurementType(IngredientName始終返回null)值IM,理想的情況是我想對httppost成分將與所有的填充上我將能夠配料填充

我需要做什麼才能從我的局部視圖獲取值到我的控制器?

回答

2

找到例子你爲什麼不看看的MVC Controlstoolkit

我想他們會做你想要什麼。

+0

歡呼謝恩。該工具包非常酷! –

0

沒有得到太多的細節。你可以改變public ActionResult Create來使用FormCollection而不是視圖模型嗎?這將允許您查看即將通過的數據。如果你可以發佈,這將有所幫助。

您的視圖模型通過使用綁定獲取填充 - 如果您還沒有閱讀它,這可能是一個好主意。最後,我會考慮將你的列表或枚舉包裝成一個單一的視圖模型。

0

可能的問題

問題可能與新的部分,你只是渲染不能正確地與您的視圖模型您發佈以後綁定的事實所在。

如果您檢查與螢火蟲的元素,然後在局部元素應該被命名爲/ Id'ed是這樣的:成分[X] .Property1,成分[X] .Property2

在你的情況,當你添加一個部分時,他們可能只是叫做Property1,Property2

可能的解決方案

給你的財產在你的部分與您的配料表對應的正確名稱。事情是這樣的:

@Html.TextBox("Ingredients[x].Property1","") 

中,渲染你的部分後,只需更改所有的名字連接ID的使用jQuery正確的值。

0

發生這種情況的原因是部分視圖中的字段名稱不適合默認的ModelBinder約定。您應該分析字段在部分視圖中的名稱。

此外,你應該實現正確的方式綁定收藏到MVC控制器。你可以在Phil's Haack post

0

假設RecipeViewModel是被供應給局部視圖模型,儘量只接受像這樣在您的帖子控制器回:

[HttpPost] 
public ActionResult Create(RecipeViewModel vm) 
{ 
    // 
} 

你應該得到填充形式提供的所有數值模型。

相關問題