Pascal
Pascal

Reputation: 12885

Get changed item from DropDownListFor into another form

I have 3 forms each has access to its own Delete/Create/Edit action on server side.

How can I let my Create/Edit form know of my change in the DropDownListFor ?

Passing the initial title value works with the Create/Edit action. So the problem is the change event.

index.cshtml

@using (Html.BeginForm(MVC.Configuration.Addresses.ActionNames.Delete, MVC.Configuration.Addresses.Name, new { @area = MVC.Configuration.Name }, FormMethod.Post, HtmlAttributes.Form))
        {

            <div class="form-group required">
                @Html.LabelFor(m => m.Title, HtmlAttributes.Label)
                <div class="col-md-6">
                    @(Html.Kendo().DropDownListFor(m => m.Title)
                                  .BindTo(Model.Addresses.OrderBy(order => order.Text))
                                  .HtmlAttributes(HtmlAttributes.KendoControl))
                </div>
            </div>

            <input type="submit" value="Delete" class="btn btn-default" />
        }

        @using (Html.BeginForm(MVC.Configuration.Addresses.ActionNames.Edit, MVC.Configuration.Addresses.Name, new { @area = MVC.Configuration.Name }, FormMethod.Get, HtmlAttributes.Form))
        {
            @Html.HiddenFor(p => p.Title)
            <input type="submit" value="Edit" class="btn btn-default" />
        }
        @using (Html.BeginForm(MVC.Configuration.Addresses.ActionNames.Add, MVC.Configuration.Addresses.Name, new { @area = MVC.Configuration.Name }, FormMethod.Get, HtmlAttributes.Form))
        {
            @Html.HiddenFor(p => p.Title)
            <input type="submit" value="Add" class="btn btn-default" />
        }

Upvotes: 0

Views: 110

Answers (1)

Alberto
Alberto

Reputation: 1863

you can use 1 form with multiple buttons, you will achieve the desired result and your view will be cleaner.

As far as I know there are two main methods:

  • 1 MVC Action: You can check the value of clicked submit button in MVC action and then perform the desired things. Example given that your buttons have as name "submitButtonName".

[HttpPost] public ActionResult YourAction(string submitButtonName, YourFormModel model) { switch (submitButtonName) { case "create": CreateMethod(model); break; case "edit": EditMethod(model); break; case "delete": DeleteMethod(model); break; } }

  • 3 MVC Actions: You can change the form target action on button click using javascript. Example given that your buttons have as class "submitButtonClass".

    $(".submitButtonClass").on("click", function(e){ e.preventDefault(); $('#yourFormId').attr('action', $(this).val()).submit(); });

I wrote the code quickly without testing it but it should work :)

Have a nice day,

Alberto

Upvotes: 1

Related Questions