2

我正在使用 asp.net mvc 4,我有以下场景

Cities           Places     Events
------           ------------------
City 1          |                  
City 2          |
                |

左侧导航(城市)列出了数据库中的所有城市。地点和事件也是动作方法的链接。

<li>@Html.ActionLink("Places", "Places", null, new{id="placeslink"})</li>
<li>@Html.ActionLink("Events", "Events", null, new{id="eventslink"})</li>

我正在使用以下脚本(jQuery)异步加载地点和事件

$('#placeslink').click(function (event) {
    event.preventDefault();

    var url = $(this).attr('href');
    $('#content').html(ajax_load).load(url);
});

$('#eventslink').click(function (event) {
    event.preventDefault();

    var url = $(this).attr('href');
    $('#content').html(ajax_load).load(url);
});

它工作正常,并在单击地点和事件链接时从数据库中填充页面上的所有地点(不是特定城市)和事件。

现在我想要实现的是,当用户在查看地点时单击一个城市,只显示该城市中的地点,如果选择了事件,同一个城市链接应该显示该城市中的事件。类似地,如果选择了城市(例如城市 1)并且用户单击地点,则显示所选城市中的地点,并且如果她单击事件,则显示所选城市的事件。

我有以下操作方法

public ActionResult Places()
{
  if (Request.IsAjaxRequest())
  {
     ....  
     return PartialView(model);               

  }
  return View();
}

它非常令人困惑,我想不出一种方法来为城市、地点和事件生成适当的链接并实现上述结果。

4

1 回答 1

1

试一试,我会制作这样的视图模型

public class PlacesAndEventsViewModel
{
    public string LocationOption { get; set; }  //places or events

    public List<Place> Places { get; set; }

    public List<Event> Events { get; set; }

    public int? CityID { get; set; }
}

还有我的控制器

//this is get
public ActionResult  ShowLocations()
{
    var model = new PlacesAndEventsViewModel();

    model.CityID = null; //or any default value
    model.LocationOption = "places"; //or any default value
    model.Places = new List<Place>(); //or GetAllPlacesFromDB();
    //You can do the same for events but I think you need one at a time

    return View("ViewPlaces", model);
}

[HttpPost]
public ActionResult  ShowLocations(PlacesAndEventsViewModel model)
{
    if(model.LocationOption == "places")
    {
        model.Places = GetAllPlacesByCity(model.CityID);
        return View("ViewPlaces", model);   //All these could be partial view
    }
    else if(model.LocationOption == "cities")
    {
        model.Events = GetAllEventsByCity(model.CityID);
        return View("ViewEvents", model);  //All these could be partial view
    }
    else
    {
        return View("ViewPlaces", model);  //All these could be partial view
    }
}   

您可能需要将 Ajax 更改为 $.ajax()

  $.ajax({
     url: '@Url.Action("ShowLocation"),
     data: { LocationOption: '@Model.LocationOption', CityID: @Model.CityID }
  });
于 2013-03-13T09:49:54.863 回答