【发布时间】:2026-02-24 01:10:01
【问题描述】:
我有一个 Index 视图,当我单击 Edit 按钮时,我发布到 Edit 视图(通过控制器)并显示引导模式弹出窗口。
通过发布到 Edit 视图,控制器/视图会自动处理在模式弹出窗口上获取和显示正确数据。
一旦我在我的 编辑 视图中出现对话框并单击 关闭 按钮,我只想链接回来 再次到 Index 页面;但相反,我的 url 路径出现错误。我要链接的新路径正在“添加”到原始路径,而不是替换它。
我在 Close 按钮的点击事件中使用了 Url.Action 方法(我验证了它正在点击)并验证了 location.href url正是您在代码中看到的 url 变量中的内容。
我需要做什么才能正确链接回 Index url?
索引视图
<a href="@Url.Action("Edit", "Category", new { area="Categories", id = item.CategoryID })"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span>Edit</a>
编辑控制器
// GET: Categories/Edit/5
public async Task<ActionResult> Edit(short id)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = await db.GetCategoryIDAsync(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
编辑视图
@model YeagerTechDB.Models.Category
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="modal" id="categoryEditModal" tabindex="-1" role="dialog" aria-labelledby="categoryModal-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="categoryModal-label">Category Description</h4>
</div>
<div class="modal-body">
<div class="form-group">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.CategoryDescription, new { @class = "control-label required col-offset-1 col-lg-3 col-md-3 col-sm-3 col-xs-3" })
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
@Html.EditorFor(model => model.CategoryDescription, new { @class = "form-control" } )
@Html.ValidationMessageFor(model => model.CategoryDescription, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="btnCloseCategory">Close</button>
<button type="submit" class="btn btn-primary" id="btnSaveCategory">Save</button>
</div>
</div>
</div>
</div>
<div>
@Html.Hidden("categoryEditUrl", Url.Action("Edit", "Category", new { area = "Categories" }))
@Html.Hidden("catID", Model.CategoryID)
</div>
@section Scripts {
<script>
$(document).ready(function ()
{
if (typeof contentEditCategory == "function")
contentEditCategory()
});
</script>
}
编辑视图的 JS
$('#btnCloseCategory').click(function (e)
{
var url = '@Url.Action("Index", "Category", new { area = "Categories" })';
location.href = url;
return false;
});
模态弹窗图片
错误图片
【问题讨论】:
-
你的 JS 在外部文件中吗?如果是这样,它将不会通过 Razor 引擎并将 @Url.Action 转换为实际 URL。将 JavaScript 放在视图中或硬编码外部文件中的值
标签: javascript jquery asp.net asp.net-mvc twitter-bootstrap