AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

ASP.NET MVC jquery checkboxlist post?

post methot:

function PostChartValues(meter_id, range_type_id, start_date, end_date) {
var values = $("#type_selection").val();
//values = expected values as string array
$.ajax({
    url: '/Widget/GetMeterReadingsTimeSeries',
    type: 'POST',
    data: { MeterType: meter_id, DateRangeType: range_type_id, StartDate: start_date, EndDate: end_date, Parameters: values },
    beforeSend: function () {
        $("#chart_loading_div").show();
    },
    complete: function () {
        $("#chart_loading_div").fadeOut();
        $(".grids").jqGrid('GridUnload');
        grid(meter_id, range_type_id, $("#start_date").val(), $("#end_date").val());
    },
    success: function (result) {
        $("#chart").html(result);
    },
    error: function (result) {
        alert("Seçilen kritere uygun veri bulunamadı!");
    }
});   //end ajax
} //end PostChartValues

action method:

public ActionResult GetMeterReadingsTimeSeries(int MeterType, int DateRangeType, DateTime? StartDate, DateTime? EndDate,string[] Parameters)
{
    // ...
    return PartialView("_TimeSeries", chart);
}

I debugged it. only Parameters array is null. Is there an other way to post array with jquery post?

Thanks.

Upvotes: 2

Views: 3094

Answers (2)

Stuart Hallows
Stuart Hallows

Reputation: 8953

An alternate way to get the selected values if you're using Underscore:

var selectedValues = _.map($("#myDiv:checked"), function (item) { return $(item).val(); });

Upvotes: 0

ziyasal
ziyasal

Reputation: 558

You can post selected values as string then you parse it back to array. I have created basic sample below,

Markup

<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#someButton').click(function () {
            var selectedValues = [];
            $('#MyDiv input:checked').each(function () {
                selectedValues.push($(this).val());
            });
            console.log(selectedValues);
            $.ajax({
                url: 'someurl',
                type: 'POST',
                data: { values: selectedValues.join(",") }
            });
        });
    });
</script>
<button id="someButton">Do Ajax</button>
<div id="MyDiv">
    <input type="checkbox" value="test1" />
    <input type="checkbox" value="test2" />
    <input type="checkbox" value="test3" />
</div>

Controller

public class HomeController : Controller
    {       
       public void Test(string values)
        {
            string[] selectedValues = values.Split(',');
        }
    }

Upvotes: 3

Related Questions