将JavaScript创建的复选框传递到控制器以保存到表格吗?

时间:2019-02-19 03:51:30

标签: javascript c# asp.net-mvc .net-core

我有从Google地图搜索结果动态创建的复选框。我希望能够将这些传递给控制器​​,以便可以将它们添加到数据库中,然后在以后查询。

现在我有一个供用户搜索城市的视图,输入被发送回控制器以呈现新视图,以用附近的位置填充Google地图。使用javascript作为复选框,将附近的位置动态添加到<div>中。

我试图将复选框作为字符串数组和模型类的数组传递。我只在使用string []的控制器中接收到结果,但随后无法将它们保存到数据库中。

    [HttpPost]
    public IActionResult Itinerary(string[] destination)
    {
        foreach (var item in destination)
        {
            _context.Itinerary.Add(item);  // error: '"Argument 1: Cannot convert from 'string ' to NameSpace.Model.Itinerary"
        }

        _context.SaveChanges();
        return View();
    }

JavaScript复选框

function createMarkers(places) {
    var bounds = new google.maps.LatLngBounds();
    var placesList = document.getElementById('places');
    for (var i = 0, place; place = places[i]; i++) {
        var image = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
        };
        var marker = new google.maps.Marker({
            map: map,
            icon: image,
            title: place.name,
            animation: google.maps.Animation.DROP,
            position: place.geometry.location
        });

        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "destination";
        checkbox.value = place.name;
        checkbox.id = "id";
        checkbox.setAttribute("asp-for","LocationName");


        var label = document.createElement('label')
        label.htmlFor = "id";
        label.appendChild(document.createTextNode(place.name));


        placesList.appendChild(label);
        placesList.appendChild(checkbox);

将表单过帐复选框回传给控制器

@using (Html.BeginForm("Itinerary", "Itinerary", FormMethod.Post))
{ 

        <div multiple id="places" > </div>
        <button id="more">More results</button>

    <input type="submit" value="Finished"/>
}

1 个答案:

答案 0 :(得分:0)

正如您所指出的那样,错误在此行上:

 _context.Itinerary.Add(item);  // error: '"Argument 1: Cannot convert from 'string ' to NameSpace.Model.Itinerary"

您需要创建一个Itinerary

 _context.Itinerary.Add(new Itinerary { Destination = item });