theHussle theHussle - 3 months ago 32
ASP.NET (C#) Question

Trying to pass a variable to Jquery from Razor

So I'm working on a project in ASP.net and have a situation where I've created a form that provides users a drop down menu to select from. On top of this the Jquery below allows the user to add additional drop down fields. This works.
Now my problem stems from the first drop down has a list of institutes which works fine as its being populated from the C# in the html form.

When the user selects to add another drop down that box is just empty. I've tried adding the C# directly to the Jquery but this doesn't work.

I'm not overly experienced with ASP.net or MVC both of which I'm using for the project, what is the best way to go around passing the values into Jquery so I can add list to the drop down?

Here is the code below

<script>
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" /></select><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});

$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>


Here is the HTML

<div class="col-md-3 BasicInfoFormLabelColumn">
<label for="restrictedInstitute" class="formLabel">Restricted Institutes: (Can't Apply)</label>
</div>
<div class="col-md-3 input_fields_wrap">
<select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" id="selectRestricted" />
<option value="0">Please Select</option>
@foreach (var item in Model.institute)
{

if (@item.TradingName != null && @item.TradingName != " " && @item.TradingName != "")
{
<option value="@item.TradingName">@item.TradingName</option>
}
}
</select>
<div class="row">
<div class="col-md-12 BasicInfoFormRow ">
<button class="add_field_button addMore">+Add More institutes</button>

</div>
</div>
</div>


I've added a couple images to help clarify what I'm trying to do.

Answer

Its happening because U only append select without its option inside you Jquery. I recommend using AJAX and partial view to achieve ur goal. First, separate the rendering of dropdownlist into another cshtml, for example the name is Institute.cshtml

Institute.cshtml

@model xxxx.Model.Institute //model would be your institute
<select  style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" id="selectRestricted" />
    <option value="0">Please Select</option>
    @foreach (var item in Model)
    {
        if (@item.TradingName != null && @item.TradingName != " " && @item.TradingName != "")
        {
           <option value="@item.TradingName">@item.TradingName</option>
        }
    }
</select>

Then you call it as partialview in your HTML

<div class="col-md-3 input_fields_wrap">
        @Html.Partial("Institute", Model.Institute)
        <div class="row">
            <div class="col-md-12  BasicInfoFormRow ">
               <button class="add_field_button addMore">+Add More institutes</button>
            </div>                       
        </div>
    </div>

And add the partialview in your Controller

xxController

PartialViewResult Institute()
{
     return PartialView();
}

This is the first step to separate your dropdownlist into another partialView The second step is calling an ajax in your add click button, and fetch the result using this partialView

javascript

$(document).ready(function () {
    var max_fields = 10; //maximum input boxes allowed
    var wrapper = $(".input_fields_wrap"); //Fields wrapper
    var add_button = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function{ //on add input button click
        if (x < max_fields) { //max input box allowed
            x++; //text box increment
            $.ajax({
                    url: '@Url.Action("AddDropdown", "YourController")',
                    type: "GET",
                    success: function (result) {
                        $(wrapper).append(result);
                    }
                });
        }
    });

    $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

this Javascript means, when u click Add button, you will request to your controller using Ajax. Then the controller will help you to render the dropdownlist and send the result back to your Client. So, you need to add another function in your controller to receive this Ajax request

xxController

public ActionResult AddDropdown()
{
    Model.Institute Result = new Model.Institute()
    //you can generate your Model.Institue in here

    Return PartialView("Institute", Result); //this will render Result with Institute.cshtml
}

after this, you can add dropdownlist into your html with the click add button