2

I've a view that is more or less exactly the same for 3 different controllers. The only difference is where they post a form. All those controllers derives from the same base-class and the view contains a form which will post to one of the actions in that base class.

My view currently looks like this:

@model Models.Forms.ContactPersonForm
@{
    Layout = null;
}
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title">Edit contact person</h4>
</div>
@using (Html.BeginForm<ProductsController>(x => x.EditContactPerson(null), FormMethod.Post))
{
    <div class="modal-body">
        @Html.EditorForModel()
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">
            <span class="fa fa-times" area-hidden="true"></span> Close
        </button>
        <button type="submit" class="btn btn-primary">
            <span class="fa fa-floppy-o" area-hidden="true"></span> Save
        </button>
    </div>
}

The view above works fine. But I want to reuse it for another controller which also inherits the same base controller (and posts to the EditContactPerson action). Therefore I want to specify in the model which controller to post to. I know I can use the string overload as such:

@Html.BeginForm("EditContactPerson", "Products", FormMethod.Post)

or

@Html.BeginForm(Model.Action, Model.Controller, FormMethod.Post)

but I really want to use the Expression instead, like so:

@Html.BeginForm<ProductsController>(x => x.EditContactPerson(null), FormMethod.Post)

Is there a way I can use the model to render the form using an Expression from the model?

Something similiar to:

@Html.BeginForm<Model.ControllerType>(Model.ActionExpression, FormMethod.Post)
Community
  • 1
  • 1
smoksnes
  • 10,509
  • 4
  • 49
  • 74

1 Answers1

0

What about something like that:

@model Models.Forms.ContactPersonForm
@{
    Layout = null;
}
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title">Edit contact person</h4>
</div>
@if (Model.XYZ == "...")
{
    using (Html.BeginForm<ProductsController>(x => x.FirstAction(null), FormMethod.Post))
    {
        Html.RenderPartial("FormContentPartialView");
    }
}
else
{
    using (Html.BeginForm<ProductsController>(x => x.SecondAction(null), FormMethod.Post))
    {
        Html.RenderPartial("FormContentPartialView");
    }
}
Dawid Rutkowski
  • 2,658
  • 1
  • 29
  • 36