【发布时间】:2015-04-06 10:50:39
【问题描述】:
我将 asp.net mvc 应用程序部署为 IIS 中一个网站下的应用程序。
控制器:
public ActionResult Index()
{
List<SelectListItem> ddlCountry = countryService.GetCountries().Select(d => new SelectListItem() { Text = d.Name, Value = d.Id.ToString() }).ToList();
ddlCountry.Insert(0, new SelectListItem() { Text = string.Empty, Value = string.Empty });
ViewData["ddlCountry"] = ddlCountry;
}
public ActionResult GetCities(int Id)
{
if (!Convert.ToBoolean(ConfigurationManager.AppSettings["InDev"]))
{
return Redirect("http://example.com/");
}
var list = cityService.GetCities(Id).Select(d => new {Id = d.Id, Name = d.Name }).ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
查看:
<tr>
<td>@Html.LabelFor(model => model.CountryId, "Country Name")</td>
<td>@Html.DropDownListFor(model => model.CountryId, ViewData["ddlCountry"] as List<SelectListItem>)</td>
<td>@Html.ValidationMessageFor(model => model.CountryId)</td>
</tr>
<tr>
<td>@Html.LabelFor(model => model.CityId, "City Name")</td>
<td>@Html.DropDownListFor(model => model.CityId, ViewData["ddlCity"] as List<SelectListItem>)</td>
<td>@Html.ValidationMessageFor(model => model.CityId)</td>
</tr>
JavaScript:
$(document).ready(function () {
$('#CountryId').change(function () {
loadDropDown("CityId", "BookingRequest/GetCities/" + $('#CountryId').val())
$('#AreaId').html($('<option></option>').val("").html(""));
});
function loadDropDown(destinationId, Url) {
$.getJSON(Url, function (data) {
$('#' + destinationId).html($('<option></option>').val("").html(""));
$.each(data, function (index, item) {
$('#' + destinationId).append(
$('<option></option>').val(item.Id).html(item.Name)
);
});
});
}
});
当我将它作为网站下的应用程序部署到 IIS 时,它会正确加载城市。 URL 就像http://www.example.com/applicationname/BookingRequest。并且当我更改国家/地区下拉值时,它会执行 get on http://www.example.com/applicationname/BookingRequest/GetCities/2 并且一切正常。
但是当我在 Visual Studio 上运行它并更改它在错误 URL 上执行 getCities 的国家/地区时:http://localhost:506084/BookingRequest/BookingRequest/GetCities/2
我的问题是为什么这在从 Visual Studio 运行的 localhost 和 IIS 上表现不同?是因为在 IIS 的网站内部署为 Web 应用程序吗?还是和我的浏览器有关?
这是来自 IE 的 Web 开发工具的请求的快照。
【问题讨论】:
-
您没有传递正确的(相对)网址。遵循标准做法并使用
'@Url.Action("GetCities", "BookingRequest")',以便正确生成您的 url'(在这种情况下使用前导斜杠 -/BookingRequest/GetCities -
@StephenMuecke 但是那个 ajax 调用在不同的 javascript 文件中。那么我将如何使用
@URLhelper 在 javascript 文件中生成 url。以下 Jinesh 的回答是否被认为是最佳实践? -
您可以这样做,尽管最常见的解决方案是将 url 添加到元素
data-属性中 - 例如@Html.DropDownListFor(model => model.CountryId, ...... new { data_url = "Url.Action("..", "..") })然后通过change()事件访问它 - 例如var url = $(this).data(url); -
在项目属性 > Web > 单击单选按钮“使用本地 IIS 服务器”。通过这样做,您的两种行为将是相同的。
标签: c# jquery ajax asp.net-mvc