ASP.NET MVC:两个控制器操作重用视图
“添加”和“编辑”视图通常或多或少相同。如何重用视图以便 Foos/Add
和 Foos/Edit/[Id]
都使用它?行动会是什么样子?
谢谢
'Add' and 'Edit' views are typically more or less identical. How can I reuse a View so that Foos/Add
and Foos/Edit/[Id]
both use it? What would the actions look like?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用 jQuery ajax。单击“添加”或“编辑”将调用服务操作,该操作将返回相同的 PartialView(如果您想重用它)。
然后,在 ajax 调用的成功函数中,您只需将返回的 html(从 PartialView )放入页面(或弹出窗口)的特定部分。
漂亮干净,无需重新加载页面...
I would use jQuery ajax. Clicking on Add or Edit would call serve action which will return the same PartialView (if you want to reuse it).
Then, in the success function of ajax call, you have just to put returned html (from that PartialView) into certain part of your page (or popup).
Nice and clean and no page reload...
您可能需要考虑使用编辑器模板,而不是重复使用相同的视图。编辑器模板是用于编辑和/或插入数据的部分视图。
这将需要单独的视图,但代码将是最少的。大部分代码将位于模板中,您可以将其重复用于“添加”和“编辑”操作。
创建模板,您的添加视图将如下所示(Razor):
并且您的编辑视图将如下所示:
You may want to consider using an Editor Template as opposed to reusing the same View. An Editor Template is a partial View that is used for editing and/or inserting data.
This would require separate views but the code would be minimal. The bulk of the code would be in the template which you would reuse for both the Add and Edit actions.
After you create your template, your Add View would look like (Razor):
And your Edit View would look like:
只需在调用
View()
方法时指定视图名称,例如您的视图必须为
Add
操作处理 null/空模型值,或者您可以使用默认值填充模型价值观。Simply specify the view name when calling the
View()
method likeYour view will have to handle null/empty model values for the
Add
action or you could populate your model with default values.