fcaldera
fcaldera

Reputation: 582

Multiple dropdownlist postback in MVC3

I have the following code on a view:

@using (Html.BeginForm()) {

    <div class="select-box form">
        <p>
            <strong>Select transcript name to view:</strong>
            @Html.DropDownList("license", (SelectList)ViewBag.Licenses, new { onchange = "this.form.submit();" })
        </p>
    </div>
    <div class="select-box form">
        <p>
            <strong>You may have multiple periods for each transcript name:</strong>
            @Html.DropDownList("period", (SelectList)ViewBag.Periods, new { onchange = "this.form.submit();" })
        </p>
    </div>
}

I need to implement some logic depending on which dropdown cause the postback. I'm thinking to add a hidden input and set value of the control name by jQuery before submit the form, but I'm wondering if there is a 'native' way to do this.

This is my controller signature:

public ActionResult Checklist(int license, int period) 

Thanks in advance!

Upvotes: 0

Views: 2213

Answers (2)

The Godfather
The Godfather

Reputation: 929

Use something like this. (Here you are calling the action method instead of submitting the form)

Which ever dropdown caused the change will pass non zero value to the action method and the other will pass 0.

 @Html.DropDownList("license", (SelectList)ViewBag.Licenses, new { onchange = "document.location.href = '/ControllerName/Checklist?license=' + this.options[this.selectedIndex].value + '&period=0'" })
 @Html.DropDownList("period", (SelectList)ViewBag.Periods, new { onchange = "document.location.href = '/ControllerName/Checklist?license=0&period=' + this.options[this.selectedIndex].value;" })

Hope this helps!

Upvotes: 1

Shyju
Shyju

Reputation: 218702

I would apply a class to the dropdown so that my jQuery can use that as the selector criteria

 @Html.DropDownList("license", (SelectList)ViewBag.Licenses, new { @class="mySelect"})
 @Html.DropDownList("period", (SelectList)ViewBag.Periods, new { @class="mySelect"})
 <input type="hidden" id="source" name="source" value="" />

And the script is

$(function(){

 $(".mySelect").change(function(){
   var itemName=$(this).attr("name");
   $("#source").val(itemName);
    $("form").submit()
 });

});

Upvotes: 1

Related Questions