gpt4 book ai didi

c# - 动态 Action 链接

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:51 25 4
gpt4 key购买 nike

我正在使用 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();
}

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

最佳答案

试一试,我会像这样制作 View 模型

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; }
}

还有我的 Controller

//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 }
});

关于c# - 动态 Action 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15380846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com