2016-12-19 52 views
1

我試圖生成TextArea盒由控制器提供的默認值。鑑於這種標記它調用的局部視圖:MVC TextAreaFor與價值呈現空箱

@{ 
    Html.RenderAction(
     "ContentBlock", "ContentBlock", 
      new TestSiteMvc.Models.ContentModel() { ContentID = 3 } 
     ); 
} 

管窺:

@Html.TextBoxFor(m=>m.Title) 
@Model.ContentHtml<br /> 
@Html.TextAreaFor(m => m.ContentHtml) 
@Html.TextBoxFor(m => m.ContentHtml) 
@Html.TextArea("ContentHtml2", Model.ContentHtml) 
@Model.ContentHtml<br /> 

渲染生成的HTML是:

<input id="Title" name="Title" type="text" value="Home Title" /> 
Home Page Content<br /> 
<textarea cols="20" id="ContentHtml" name="ContentHtml" rows="2"></textarea> 
<input id="ContentHtml" name="ContentHtml" type="text" value="Home Page Content" /> 
<textarea cols="20" id="ContentHtml2" name="ContentHtml2" rows="2">Home Page Content</textarea> 
Home Page Content<br /> 

所以,很明顯是越來越填充ContentHtml財產。我不明白的是爲什麼TextAreaFor呈現爲一個空值。並且要清楚,當我刪除行@Html.TextBoxFor(m => m.ContentHtml),以不產生與同一ID標籤,這個問題不會消失。

控制器:

[HttpGet] 
    public ActionResult ContentBlock(Models.ContentModel mcontent) { 

     mcontent = new Models.ContentModel() { 
      ContentID = 3, 
      ContentHtml = "Home Page Content", 
      Title = "Home Title" }; 
     return PartialView(mcontent); 
    } 

型號:

public class ContentModel { 

    public int ContentID { get; set; } 
    public string Link { get; set; } 
    public string Title { get; set; } 
    public string ContentHtml { get; set; } 
    public DateTime LastModifiedDate { get; set; } 
} 
+0

不能重複這一點。 –

+0

您的控制器代碼在哪裏?使用給定的ViewModel屬性測試視圖代碼,它已經工作,您需要提供控制器操作方法來清除textarea默認值問題。 –

+0

@TetsuyaYamamoto,我添加了控制器和一些額外的代碼。謝謝。 – InbetweenWeekends

回答

1

你的GET方法有一個參數,它是你的模型,所以DefaultModelBinder用默認值初始化ContentModel和設置的ContentID3值。此時所有的值都加入到ModelState(的ContentHtmlModelStatenull - 爲string默認值)。更新屬性的值不會影響ModelState中的值。

當您返回視圖時,@Html.TextAreaFor()首先檢查ModelState,在您的情況下這是null,因此不會呈現任何值。 (如果在ModelState值沒有找到,於是,該方法檢查ViewData,最後你的模型財產的實際價值來確定渲染什麼)。

還要注意的是@Html.TextArea("ContentHtml2", Model.ContentHtml)的作品,因爲它不是你使用專門設置基於其他屬性的值過載綁定到一個模型屬性和。

正確的做法,並解決這個最簡單的方法就是在控制器方法更改爲

public ActionResult ContentBlock(int id) 
{ 
    ContentModel model = new ContentModel() 
    { 
     ContentID = id, 
     ContentHtml = "Home Page Content", 
     Title = "Home Title" 
    }; 
    return PartialView(model); 
} 

和更改視圖代碼

@{ Html.RenderAction("ContentBlock", "ContentBlock", new { id = 3 }); } 

或者,你可以添加ModelState.Clear()爲第一在控制器的方法的代碼行,以從ModelState除去所有的值(那麼​​方法將獲得從模型屬性的值)

+0

謝謝!更改控制器解決了問題。 – InbetweenWeekends