c# - 跨不同 Controller 和 View 重用局部 View (ascx)

标签 c# asp.net-mvc viewmodel

假设我有 2 个 Controller ,TopicsControllerPostsController

对于每个 Controller ,我有几个 View (索引和详细信息)。

主题(索引) View 继承 System.Web.Mvc.ViewPage<IEnumerable<MessageBoard.Models.Topic>>

主题(详细信息) View 继承System.Web.Mvc.ViewPage<MessageBoard.Models.TopicFormViewModel>
我正在使用 TopicFormViewModel,因为我要连同模型一起发送额外的数据。

Post (Details) View 继承了System.Web.Mvc.ViewPage<MessageBoard.Models.Post>

现在,我创建了一个局部 View (CreatePost.ascx),它(显然:p)用于创建一个新帖子。我希望能够对您在上面看到的所有 View 重复使用此控件。

更新
我尝试使用 <% Html.RenderPartial("New"); %> 渲染部分 View 来 self 的 Topics/Index.aspx View ,但这会导致异常

The model item passed into the dictionary is of type 'System.Data.Linq.Table`1[MessageBoard.Models.Topic]', but this dictionary requires a model item of type 'MessageBoard.Models.Post'.

现在的问题是我的局部 View (CreatePost.ascx) 接受 System.Web.Mvc.ViewUserControl<MessageBoard.Models.Post>而且我不确定如何从我上面的所有观点中传递它。

我也不确定如何将 .ascx 值提交到某个 URL(即/Topics/1/CreatePost),我该如何告诉提交按钮发布到该 URL?

提前致谢,
马尔科

最佳答案

再见马尔科

Now the problem is that my partial view (CreatePost.ascx) accepts a System.Web.Mvc.ViewUserControl and I'm not sure how to pass that from all my views above.

我不确定我是否理解“如何从我上面的所有 View 中传递它”是什么意思,但我确信您不必从您的 View 中传递 Post 实例。发生的事情是,从您的 View 中,您将调用创建 Post 模型对象的 Controller 操作,然后将其绑定(bind)到 CreatePost.ascx 部分。

I'm also unsure know how to submit the .ascx values to a certain URL (i.e. /Topics/1/CreatePost), how do I tell the submit button to post to that URL?

你有两个选择:

在您的 CreatePost.ascx 部分中,您可能正在使用一个表单。

<% using (Html.BeginForm("action", "controller", FormMethod.Post, new {} )) { %>

如果您按照我展示的方式使用,您可以将第一个和第二个参数分别更改为将阻碍您提交的 Action 和 Controller 的名称。

第二个选项是使用 jQuery。只需为您的表单设置一个 ID,然后

$("#myForm").submit(function(event) {
    //post an ajax request to the server
});

希望这对您有所帮助!

附言为了能够重用您的 CreatePost.ascx 部分,请将它放在共享 View 文件夹(母版页所在的位置)中。

关于c# - 跨不同 Controller 和 View 重用局部 View (ascx),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4065402/

相关文章:

c# - MVC - 即使没有人登录应用程序也运行计划任务

c# - 我应该使用 AutoMapper 从 ViewModel 到 Model 对象吗

android - 在许多 fragment 之间向后导航的简单方法是什么?

c# - 为什么我的测试 "propType == typeof(ObservableCollection<string>)"失败了?

c# - SimpleInjector 和 FluentValidationFactory

c# - c#中的日期时间字符串问题

c# - 将文本框中的数字乘以数量值

javascript - Jquery 中未解析 URL 名称

c# - ASP.NET MVC : What's the difference in concept between Service and Repository

c# - MVC 自定义 View 模型问题