将逗号分隔值传递给ASP.NET MVC操作方法

时间:2017-08-17 12:51:16

标签: javascript c# jquery asp.net ajax

好吧所以我基本上有一个ajax调用从html选择多个标签检索值...事实是我无法将这些值传递给我的控制器(我在控制器中得到一个空引用)

在ajax调用中检查types: $('select#opt2').val()avion: $('select#opt1').val()不是多个值,因此工作正常。当我alert($('select#opt2').val())时,我得到的值如下:GC,VSG,AA7 ......(它们用“,”分隔)

这是我的代码:

AJAX

$('select#opt2').change(function () {
            $.ajax({
                url: '@Url.Action("RetournerPostes", "Home", new { area = "Avion" })',
                data: { avion: $('select#opt1').val(), types: $('select#opt2').val() },
                type: 'POST',
                dataType: 'JSON',
            //Rest of code

CONTROLLER 这是我获得变量“types”

的空引用的地方
[HttpPost]
    public async Task<ActionResult> RetournerPostes(string avion,List<string> types)
    {
       //Rest of action

告诉我您是否需要更多信息。谢谢!

修改

添加小提琴:https://jsfiddle.net/f73jxo5v/

5 个答案:

答案 0 :(得分:2)

如果您经常绑定逗号分隔值(CSV),最简单且可维护的方法是创建名为CommaSeparatedModelBinder的 自定义模型绑定器

捕获select的更改事件并在用户选择选项时进行Ajax调用并不常见。但这取决于你。

enter image description here

enter image description here

[HttpGet]
public ActionResult RetournerPostes()
{
    return View();
}

[HttpPost]
public ActionResult RetournerPostes(string avion, 
    [ModelBinder(typeof(CommaSeparatedModelBinder))] int[] types)
{
    return View();
}

视图

@using (Html.BeginForm())
{
    <select id="opt1">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

    <select id="opt2" multiple>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
    <input type="submit" value="Submit"/>
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
    $('select#opt2').change(function () {
        var data = JSON.stringify({ avion: $('select#opt1').val(), types: $('select#opt2').val() });
        console.log(data);
        $.ajax({
            url: '@Url.Action("RetournerPostes", "Home")',
            data: data,
            type: 'POST',
            contentType: "application/json",
            dataType: 'JSON',
            success: function(msg) {
                console.log(msg);
            }
        });
    });
</script>

CommaSeparatedModelBinder

public class CommaSeparatedModelBinder : DefaultModelBinder
{
    private static readonly MethodInfo ToArrayMethod = typeof(Enumerable).GetMethod("ToArray");

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        return BindCsv(bindingContext.ModelType, bindingContext.ModelName, bindingContext)
                ?? base.BindModel(controllerContext, bindingContext);
    }

    protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
    {
        return BindCsv(propertyDescriptor.PropertyType, propertyDescriptor.Name, bindingContext)
                ?? base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
    }

    private object BindCsv(Type type, string name, ModelBindingContext bindingContext)
    {
        if (type.GetInterface(typeof(IEnumerable).Name) != null)
        {
            var actualValue = bindingContext.ValueProvider.GetValue(name);

            if (actualValue != null)
            {
                var valueType = type.GetElementType() ?? type.GetGenericArguments().FirstOrDefault();

                if (valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null)
                {
                    var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType));

                    foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' }))
                    {
                        if (!String.IsNullOrWhiteSpace(splitValue))
                            list.Add(Convert.ChangeType(splitValue, valueType));
                    }

                    if (type.IsArray)
                        return ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list });

                    return list;
                }
            }
        }

        return null;
    }
}

原始来源:CommaSeparatedModelBinder.cs

答案 1 :(得分:1)

那是因为你作为类型传递的是一个字符串对象而不是字符串列表。

您必须将types变量强制转换为字符串数组:

var array = string.split(','); 

并将其作为数组传递给方法,而不是作为列表:

[HttpPost]
    public async Task<ActionResult> RetournerPostes(string avion, string[] types)
    {

答案 2 :(得分:1)

希望这能解决你的问题:

var tit = '\xa0';
var jP = $("#jquery_jplayer_1");
var media = "http://my.icecast.stream:9000/live";
var cur = 'amp';
var space = String.fromCharCode(160);
var rec = String.fromCharCode(9899);
var refresh = '<i class="fa fa-refresh fa-spin fa-fw gradient-icon"></i>';
var fa = $(".fa");

var url = 'http://my.icecast.stream:9000/json.xsl';

var _mountPoint, p_width, marquee_dur;
var p_marquee = $('.jp-title p');

_mountPoint = '/live';

//function for parsing titles and covers
function radioTitle() {

    if (cur !== null) {

        if (cur === 'amp') { //cur - current station
            $.ajax({  type: 'GET',
                url: url,
                async: true,
                jsonpCallback: 'parseMusic',
                contentType: "application/json",
                dataType: 'jsonp',
                success: function (json) {

                    tit = json[_mountPoint]['title'];
                    getTitles();
                    getCover(true);
                    document.title = "MyWeb Radio @" + space + tit.concat(space + rec + space);
                    $('#track-title').text(tit ? tit : space);
                    //setting up 'marquee' (title) speed:
                    setSpeed();

                },
                error: function (e) {
                    console.log(e.message);
                }
            });

        } else if (cur === 'chl' || cur === 'dsc') {
            var fm = "My Web-Radio @ Chillout FM / ";
            getCover(false);
            document.title = cur ==='chl' ? fm + "Chillout" + space + rec + space : fm + "Disco" + space + rec + space;
            // console.log(cur);
        }
    }
}

//setting trackname scroll speed
function setSpeed() {
    p_width = p_marquee.width();
    if (p_width > 350) {
        marquee_dur = 0.16 * (p_width / 7.7865) + 20;
        p_marquee.css('animation', 'marquee linear infinite');
        p_marquee.css('animation-duration', marquee_dur + 's');
    } else {
        p_marquee.css('animation', 'none');
        p_marquee.css('transform', 'translate(-50%,0)');
    }
}

//bars button icon
var bars = '<i class="fa fa-bars gradient-icon" aria-hidden="true"></i>';

//getting cover image for current playing media from my.site/cover jsp page
function getCover(isMain) {
    if (isMain) {
        $.ajax({
            type: 'GET',
            url: 'cover',
            dataType: 'html',
            success: function (response) {
                $('#nowPlayingImg').html(response);
            }
        });
    } else {
        // $('#nowPlayingImg').html('<img width="110px" align="middle" src="../skin/image/music-elems.png" alt="cover">');

    }

}

//getting list of 10 recently played tracks from my.site/titles jsp page
function getTitles() {
    $.ajax({
        type: 'GET',
        url: 'titles',
        dataType: 'html',

        success: function (response) {
            $('#recent').html(bars + response);
        }
    });

}

$(document).ready(function(){

    setTimeout(function () {radioTitle();}, 2000);
    setInterval(function () {radioTitle();}, 15000);

    //setting client's timezone cookie
    var dateVar = new Date();
    var timezone = dateVar.getTimezoneOffset()/60 * (-1);
    document.cookie="TZOffset=" + timezone + ";path=/";

    //init jPlayer
    jP.jPlayer({
        ready: function () {
            $(this).jPlayer("setMedia", {
                mp3: media
            });
        },

        cssSelectorAncestor: "#jp_container_1",
        supplied: "mp3",
        useStateClassSkin: true,
        autoBlur: false,
        keyEnabled: true
    });

    setInterval(function () {
        var isPaused = jP.data().jPlayer.status.paused;

        if (isPaused) {
            jP.jPlayer("clearMedia");
            jP.jPlayer("setMedia", {
                mp3: media
            });
        }
    }, 9000);
});

//Toggle active tabs
$('#toggles').find('li').on('click', function() {
    $('#toggles').find('li').removeClass('active');
    $(this).addClass('active');
});

//Toggle play/pause icons
$(".subdiv .jp-controls a").click(function () {
    $(this).find(fa).toggleClass('fa-play fa-pause');

});

var lastAmp, lastChl, lastDsc, last;
var stream = $(".jp-audio-stream"), subDivs = $(".jp-details, .counter, .onclick-menu");

//Switching the stations
function _setMedia(str) {

    cur = str;

        switch (str) {
            case 'chl': {
                if (!lastChl) {
                    last = true;
                    $('#nowPlayingImg').html('<img width="110" align="middle" src="http://my.site/img/logo.png" alt="cover">');
                    lastChl = !lastChl;
                    lastDsc = false;
                    lastAmp = false;
                    media = "http://my.icecast.stream:9000/chillout";
                    jP.jPlayer("setMedia", {
                        mp3: media
                    });
                    stream.width(115);
                    subDivs.hide();
                    break;
                } else {
                    last = false;
                    break;
                }
            }
            case 'dsc': {
                if (!lastDsc) {
                    last = true;
                    $('#nowPlayingImg').html('<img width="110" align="middle" src="my.site/img/logo.png" alt="cover">');
                    lastDsc = !lastDsc;
                    lastChl = false;
                    lastAmp = false;
                    media = "http://my.icecast.stream:9000/disco";
                    jP.jPlayer("setMedia", {
                        mp3: media
                    });
                    stream.width(115);
                    subDivs.hide();
                    break;
                } else {
                    last = false;
                    break;
                }
            }
            case 'amp': {
                if (!lastAmp) {
                    last = true;
                    getCover(true);
                    lastAmp = !lastAmp;
                    lastChl = false;
                    lastDsc = false;
                    media = "http://my.icecast.stream:9000/live";
                    jP.jPlayer("setMedia", {
                        mp3: media
                    });
                    stream.width(473);
                    // document.querySelector('marquee').start();
                    subDivs.show();
                    break;
                } else {
                    last = false;
                    break;
                }
            }
        }

        if (last) {
            $(".jp-controls").find(fa).removeClass('fa-pause').addClass('fa-play');
        }

}

答案 3 :(得分:0)

如果您的类型=&#34; GC,VSG,AA7&#34;那么你传递一个字符串,而不是一个字符串列表,所以:

a.new C()

答案 4 :(得分:0)

types= []
var sel = $('#selectID');
for (var i=0, n=sel.options.length;i<n;i++) { // looping over the options
  if (sel.options[i].value) types.push(sel.options[i].value);
}

然后将类型传递给您的控制器而不更改您的服务器代码