我希望ListBoxFor中的所有项目都自动进入控制器

时间:2014-07-22 13:42:35

标签: c# asp.net-mvc razor visual-studio-2013 asp.net-mvc-5

这是我的模特:

public class ReportFilterEditViewModel : ViewModelBase
{
    /..../
    public List<string> IncludedProducts { get; set; }
}

这是我的观点

@Html.ListBoxFor(model => model.IncludedProducts,new SelectList(Model.IncludedProducts, "Name")})
<input type="submit" value="Save" id="saveFilter" class="button" />

重点是......我想在不选择列表的情况下将所有元素传递给控制器​​。 请帮帮我!提前致谢。 伊戈尔

1 个答案:

答案 0 :(得分:0)

//首先在View中的Javascript中执行以下操作:

 var data = [@Html.Raw(String.Join(",", Model.IncludedProducts.Select(i => "'" + i + "'")))];

//Pass the data array to the controller 

  $.ajax({
                type: 'POST',
                url: '@Url.Action("GetProducts", "Home")',
                contentType: 'application/json',
                data: JSON.stringify(data),
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('Error while communicating with controller!');
                    }
            }).done(function (result) {
               // console.log(result.Success);
                    if (result.Success == 'true') {
                        console.log('sent to the controller');

                    }
                    else {

                        console.log("error sending data");
                    }
                });


//then in your Controller
[HttpPost]
Public JsonResult GetProducts(List<string> model)
{

//do whatever you want with the model coz that's your product list


}