部分视图(.ascx)中的Html.TextBox(“Title”)从父视图中获取值“Title”

时间:2010-11-01 20:14:55

标签: c# asp.net-mvc partial-views

在我的论坛项目中,我有一个部分视图(.ascx),用于添加新的论坛帖子。论坛帖子位于“主题(类别)”内,这两个表都有一个名为Title的列。

现在的问题是,当我将局部视图放在Topic页面上时,它会自动从Topic中抓取Title值,从而用Topic Title填充我的Title Textbox。 不理想!

CreatePost.ascx内的代码只是

<label for="Title">Title</label>
<%= Html.TextBox("Title") %>

我已尝试将其更改为<%= Html.TextBox("Post.Title") %>,但文本框值未发布。

这是正常的行为吗?有没有一种方法可以摆脱它而不用Javascript清除它?

我甚至尝试使用第二次重载Html.TextBox("Title", "some value")来设置一个值,但这只是被覆盖了。

请帮忙!

3 个答案:

答案 0 :(得分:2)

如果您使用的是ASP.NET MVC 2,则应始终使用强类型帮助程序来正确处理绑定:

<%= Html.TextBoxFor(x => x.Category.Title) %>

答案 1 :(得分:0)

尝试以下方法:

CreatePost.ascx

   <label for="Title">Title</label>
   <%= Html.TextBox("Title") %>

YourController.cs

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreatePost(string Title) {
    // do something with Title
    return View();
}

需要确保在

之间呈现CreatePost.ascx
<% using (Html.BeginForm()) { %>....
  ..
  <% Html.RenderPartial("CreatePost.ascx");
  ..
  ..
<% } >
在您的视图中

希望这会有所帮助......

答案 2 :(得分:0)

听起来问题在于您用于渲染局部视图的代码。 RenderPartial将默认从父视图传递模型,因此您在部分中显示主题标题时看到的行为。您可以覆盖它 - RenderPartial的一个参数允许您传入新模型。

类似的东西:

<% Html.RenderPartial("CreatePost.ascx", new Post());%>

将新模型传递给局部视图(在本例中为空帖子)。

相关问题