问题
Problem:
In my application I have provide the user a selection screen for something in several places (that is, the same selection screen has to be used in several actions).
Solution:
I've come up with the following solution: pass the return action and controller to action which handles the entity selection.
Example:
Suppose that there are several places in the application where the user has to select an instance of SomeEntity
, so I added the following action to that entity controller:
public class SomeEntityController : Controller
{
/* ... */
public ViewResult Select(string returnAction, string returnController)
{
var selectableEntities = ...;
return View(
new SelectionViewModel<SomeEntity>
{
Entities = selectableEntities,
ReturnAction = returnAction,
ReturnController = returnController,
});
}
}
In the view for that action (Views/SomeEntity/Select.aspx) I put something like this:
<table>
<tr>
<th>Select</th>
<th>SomeProperty<th>
</tr>
<% foreach (var entity in Model.Entities) { %>
<tr>
<td>
<%: Html.ActionLink("Select", Model.returnAction, Model.returnController, new { entityId = entity.id }) %>
</td>
<td><%: entity.SomeProperty %></td>
</tr>
<% } %>
</table>
Then, if I need the user to select a SomeEntity
in other controller I can do this:
public class OtherController : Controller
{
public ActionResult SelectSomeEntity()
{
return RedirectoToAction("Select", "SomeEntity", new { returnAction = "ActionThatNeedsAnEntity", returnController = "Other" });
}
public ActionResult ActionThatNeedsAnEntity(int entityId)
{
// here I can use the selected entity
}
}
The last piece of code is just an example of how to use the SomeEntity
selection action. Instead of the SelectSomeEntity
action, there could be a more complex action which performs some checks to see if an entityId
is already selected (e.g. stored in the session) and then decide whether to call SomeEntity/Select
or not
Question:
The above works fine, but I’m new to ASP.Net MVC 2 so I don’t know if there is other (standard) solution for this.
Is this approach correct/neat? Have you solve this same situation differently?
回答1:
I could be misunderstanding your problem, but I think that Partial Views would be the "standard" solution you're looking for.
Partial Views are just that, small views that can be inserted into other views. Things like entry forms or displays of data can be put into a partial view and added to the regular view. They greatly simplify code.
They're simple to make. When you go to make a regular view, just check the "partial view" box in the window (i. e. after right-clicking in the solution explorer and selecting the "add view" option). You can then throw this into any full view by using <%: Html.Partial("myPartialView") %>
. You can easily pass a Model to the partial view as well by doing <%: Html.Partial("myPartialView", Model) %>
来源:https://stackoverflow.com/questions/4635893/asp-net-mvc-2-reusing-controller-view-by-indicating-return-action-and-controll