2014-02-07 73 views
0

我是初学者,我认为我的问题非常明显,但我陷入了困境!如何将自定义模型绑定到TextBoxFor

在MVC中,并试图将不是我视图的主模型的自定义模型(类)传递给我的控制器。 我的剃刀代码如下:

@helper CreatForm() 
    { 
     MyViewModel myModel = new MyViewModel(); 
     using (Html.BeginUmbracoForm("Post", "ShowPost", FormMethod.Post, new { @class = "formCM" })) 
    { 
     myModel.PostNode = Node.GetCurrent(); 
     <div class="row"> 
      @Html.TextBoxFor(x => myModel.Name, new Dictionary<string, object> { { "placeholder", "Name" } }) 
     </div> 
     <div class="row"> 
      @Html.TextBoxFor(x => myModel.Email, new Dictionary<string, object> { { "placeholder", "Email Address" } }) 
     </div> 
     <div class="row"> 
      @Html.TextBoxFor(x => myModel.Website, new Dictionary<string, object> { { "placeholder", "Website" } }) 
     </div> 
     <div class="row tall"> 
      @Html.TextAreaFor(x => myModel.Comment, new Dictionary<string, object> { { "placeholder", "Comment" } }) 
     </div> 
     <div class="row"> 
      <input type="submit" id="Submit" name="Submit" value="Submit" /> 
     </div> 
    } 
} 

点击提交按钮会带我到控制器,但是模型总是空空的。

我控制器是象下面这样:

[HttpPost] 
public ActionResult Post(MyViewModel model) 
{ 
    return this.View(); 
} 

有什么建议?我必须将此MyModel属性添加到当前页面的ViewData吗?

回答

2

创建一个需要MyViewModel的局部视图 - 这将需要使Html.TextBoxFor()以您想要的方式工作。然后从您的主视图中调用该部分视图。假设您将视图命名为“myForm”,并将其放置在共享文件夹中。然后在你的主视图:

@Html.Partial("myForm", myModel) 
+0

感谢您的回复。我用接近你的建议的方法排列了这个问题。 –