我想动态创建我的url而不是在JQuery中编写硬编码。我尝试了几种方法(在代码片段中的警告框内显示),但url的地址部分始终为null。我在其中一个用于测试的警告框中只得到了我需要的参数部分。此外,在我的项目中,我有控制器的区域。所以必须指定。最后一个警告框返回我尝试创建url时获得的最佳信息。请查看我的代码并告诉我为什么我没有正确获取我的url。如果您需要更多详情,请告诉我。谢谢。 注意:如果我在$ .post()中对url进行硬编码,它在localhost中工作正常。但是在部署到开发环境时会中断。这就是为什么必须动态创建网址。
这是我的html代码与此部分有关。
<td>
<a href="#" alt="Set Private" id="publicImage@(photo.ID)" data-photoid="@photo.ID" class="view @(photo.IsPublic ? "" : "hide")" title="Set this photo to not public.">Public</a>
<a href="#" alt="Set Public" id="privateImage@(photo.ID)" data-photoid="@photo.ID" class="noView @(photo.IsPublic ? "hide" : "")" title="Set this photo to public.">Private</a>
</td>
这是我的剧本。它直接写在html代码之后的html页面中。
<script type="text/javascript">
$(document).ready(function () {
$("a[id*='publicImage']").click(function () {
var pid = $(this).data("photoid");
var url = @Url.Action("Status", "Photos", new { Area = "Account" });
alert(@Url.Action("Status", "Photos", new { Area = "Account" }))//returns ""
alert(@Html.Raw(@Url.Action("Status", "Photos", new { Area = "Account" }))); //returns ""
alert(@Html.Raw(Url.Action("Status", "Photos", new { Area = "Account" }))+'?id=' + pid + '&status=False'); // returns "NaN&status=False"
alert('@Url.Action("status", "photos", new { Area = "account" })?id=' + $(this).data("photoid") + '&status=False'); // returns "?id=703548&status=False"
$.post(
url,//'/account/photos/' + id + "/status/False",
function () {
$("#publicImage" + id).addClass("hide");
$("#privateImage" + id).removeClass("hide");
}
)
});
这是我的控制器操作方法。
[HttpPost]
[Route("{id}/status/{status}")]
public virtual ActionResult Status(int id, bool status)
{
_photosClient.SetPublicStatus(id, status);
return RedirectToAction(MVC.Account.Photos.Index());
}
答案 0 :(得分:0)
@Url.Action("Status", "Photos", new { Area = "Account" })
返回一个字符串。
因此,您需要引用双引号或单引号。 例如,
var url = "@Url.Action("Status", "Photos", new { Area = "Account" })";
答案 1 :(得分:0)
嗨正如建议一样,因为你在变量var url = @Url.Action("Status", "Photos", new { Area = "Account" });
中获取了url,只需检查断点是什么值,如果它对于如下所示的警报不为空,则分配:
alert(url);
我想要解决的一件事就是,
根据你的注意:如果我在$ .post()中对url进行硬编码,它在localhost中工作正常。但是在部署到开发环境时会中断。这就是为什么必须动态创建网址。
对于这个笔记问题,你可以把网址加上双点../status/photos
,我遇到了这个问题并解决了这个问题。
有用的链接:https://softwareengineering.stackexchange.com/a/186719
由于
KARTHIK