簡體   English   中英

具有子對象的模型視圖,其中子對象充當強類型部分視圖的模型

[英]View with model that has children that act as model for strongly typed partial views

我有一個包含啟動表單的主頁的系統:

@model Stuvo_Intakeformulier.Models.CaterRequest

@using (Html.BeginForm(null, null, FormMethod.Post, new { id="fooData", @class="form-horizontal", role="form"}))
        {
         <div id="generalInfo" style="display:none">
              @{Html.RenderPartial("Food", Model.foodInfo);}
         </div>

         <div id="studyInfo" style="display:none">          
               @{Html.RenderPartial("Drinks", Model.drinkInfo);}
               <input type="submit" value="Bevestigen">
        ....

使用父模型

public class CaterRequest
{
    public CaterRequest()
    {
        foodInfo = new Food();
        drinkInfo = new Drinks();
    }

   public Food foodInfo { get; set; }
   ....

子模型如下:

public class Food
{
    [Required(ErrorMessage = "BlaBla")]
    public string name { get; set; }
}

最后,局部視圖如下所示:

@model Stuvo_Intakeformulier.Models.Food

<div class="form-group">    
        @Html.LabelFor(model => Model.name, "Naam: ", htmlAttributes: new { @class = "col-sm-2 control-label" })
        <div class="col-sm-10">
            @Html.TextBoxFor(model => Model.name, null ,htmlAttributes: new { @class = "form-control" })
        </div>
        <div class="col-sm-offset-2 col-sm-10">
            @Html.ValidationMessageFor(model => Model.name)
        </div>
    </div>

顯然,發布時我的model.foodInfo.name將為空,因為在我的局部視圖中,name屬性是name而不是foodInfo.name 我可以通過使用@Html.TextBox('foodInfo.name'來更改@Html.TextBoxFor(model => Model.name..這是我絕對需要的東西。

我想知道對這個問題最好的解決方案是什么? 有沒有簡單的方法來解決這個問題? 什么是最干凈的解決方案?

基本上,我希望將我的強類型局部視圖中的數據綁定到我的普通視圖中的模型中,同時仍保留強類型視圖和驗證內容。

我們使用DisplayForEditorFor模板。 它干凈,並具有您提到的所有功能。 我們有與該鏈接非常相似的工作代碼。

因此,在上面的示例中,您將需要創建一個Food.cshtml,其中可以包含與您所擁有的內容相似的內容:

@model Stuvo_Intakeformulier.Models.Food

    <div class="form-group">    
                @Html.LabelFor(model => Model.name, "Naam: ", htmlAttributes: new { @class = "col-sm-2 control-label" })
                <div class="col-sm-10">
                    @Html.TextBoxFor(model => Model.name, null ,htmlAttributes: new { @class = "form-control" })
                </div>
                <div class="col-sm-offset-2 col-sm-10">
                    @Html.ValidationMessageFor(model => Model.name)
                </div>
</div>

Food.cshtml文件上方的文件必須放置在“ Shared / EditorTemplates /”文件夾中。

然后在您的主頁上可以像這樣調用:

 <div id="generalInfo" style="display:none">
      @Html.EditorFor(m => m.foodInfo)
 </div>

public string foodInfo { get; set; } ,您是否在public string foodInfo { get; set; }有錯字public string foodInfo { get; set; } public string foodInfo { get; set; } public string foodInfo { get; set; } ,應該是public Food foodInfo { get; set; } public Food foodInfo { get; set; } public Food foodInfo { get; set; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM