奇怪的是,Visual Studio调试通过动作来查看,但没有返回浏览器

时间:2021-11-21 02:51:34

I have encountered a very strange problem. Basically, there is a Delete ActionLink. Once clicked, the code checks the condition, checks true/false, stays on current page or goes to Delete view.

我遇到了一个非常奇怪的问题。基本上,有一个删除ActionLink。单击后,代码将检查条件,检查true / false,保持当前页面或转到“删除”视图。

I have posted the solution for this scenario and got some very helpful replies. I worked on it and took it to a situation where I was about to succeed.

我已经发布了这个场景的解决方案,并得到了一些非常有用的回复。我努力工作并把它带到了我即将成功的境地。

Anyway, here are the codes

无论如何,这是代码

Index View: AJAX calls the Delete action, returns JSON or EmptyResult. If EmptyResult, then it is a failure as the original ActionLink has been disabled, AJAX will call the error function, which calls another action "Delete2".

索引视图:AJAX调用Delete操作,返回JSON或EmptyResult。如果是EmptyResult,那么由于原始ActionLink已被禁用而失败,AJAX将调用错误函数,该函数调用另一个动作“Delete2”。

<td>
                @Html.ActionLink("Edit", "Edit", new { id = item.CustomerId }, htmlAttributes: new { @class = "mergo-actionlink" }) |
                @Html.ActionLink("Details", "Details", new { id = item.CustomerId }, htmlAttributes: new { @class = "mergo-actionlink" }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.CustomerId }, htmlAttributes: new { @class = "mergo-actionlink-delete", data_value = item.CustomerId })
            </td>
        </tr>
    }

</table>

<script type="text/javascript">
    $('.mergo-actionlink-delete').click(
function () {
    var clickedId = $(this).attr('data-value');
    $.ajax({
        dataType: "json",
        url: '@Url.Action("Delete", "Customers")',
        data: { id: clickedId},
        success: function (data) {
            alert(data.message);
        },
        error: function () {
            alert("EmptyResult returns.");
            debugger;
            $.post('@Url.Action("Delete2", "Customers")', { id: clickedId });
        },
        async: false
    });
    return false;
});
</script>

Controllers:

public ActionResult Delete(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Customer customer = db.Customers.Find(id);
    if (customer == null)
    {
        return HttpNotFound();
    }

    if (customer.Orders.ToList().Count() != 0)
    {
        return Json(new { message = "This customer has order(s) attached." }, "text/plain", JsonRequestBehavior.AllowGet);
    }
    return new EmptyResult();
}

public ActionResult Delete2(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Customer customer = db.Customers.Find(id);
    if (customer == null)
    {
        return HttpNotFound();
    }
    return View(customer);
}

Delete2.cshtml

@model MergoMVC.Customer

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Customer</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.UserName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.UserName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Password)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Password)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Email)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Email)
        </dd>

    </dl>

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()

        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }
</div>

And I do have Delete.cshtml and Delete2.cshtml views for the actions. The symptom is - from debugging, Visual Studio went into Delete2 action, returned the "customer" to Delete2.cshtml view, executed it from head to toe. But the browser stayed still on index page. I think something is wrong with the return false; in the AJAX. I'm new to this, so I need some help. Thanks.

我确实有行动的Delete.cshtml和Delete2.cshtml视图。症状是 - 从调试开始,Visual Studio进入Delete2操作,将“customer”返回到Delete2.cshtml视图,从头到脚执行。但是浏览器仍停留在索引页面上。我认为回报错误有问题;在AJAX中。我是新手,所以我需要一些帮助。谢谢。

2 个解决方案

#1


1  

error: function () {
            alert("EmptyResult returns.");
            debugger;
            $.post('@Url.Action("Delete2", "Customers")', { id: clickedId });
        },

Result of a post does not refresh your page, so quick fix is to genrate an anchor with URL to controller action add id parameter and click on it or change window location with controller/action/clicked id.

帖子的结果不刷新您的页面,因此快速修复是使用URL生成锚点到控制器操作添加id参数并单击它或使用controller / action / clicked id更改窗口位置。

error: function () {
                alert("EmptyResult returns.");
                debugger;
                var a = document.createElement('a');
                // something like, not sure :)
                var hrefUri = '@Html.ActionLink("Delete2", "Customers"'); 
                a.href = hrefUri + "/" + clickedId;
                a.click();
}

You used page controller as rest api controller, not a bad thing at all but do not mix thing around because maybe someone may work on your code. Usually posting stuff via ajax you expect a JSON result, in a ajax post/get request if you return a view + model you need to update somehow the page.

你使用页面控制器作为rest api控制器,根本不是坏事,但不要混淆,因为也许有人可能会处理你的代码。通常通过ajax发布你想要JSON结果的东西,在ajax post / get请求中如果你返回一个view + model你需要以某种方式更新页面。

#2


1  

@SilentTremor Thank you so much sir. You helped me to solve the problem. The working function is (ignore all the comments):

@SilentTremor先生,非常感谢你。你帮助我解决了这个问题。工作函数是(忽略所有注释):

<script type="text/javascript">
    $('.mergo-actionlink-delete').click(
function () {
    var clickedId = $(this).attr('data-value');
    $.ajax({
        dataType: "json",
        url: '@Url.Action("Delete", "Customers")',
        data: { id: clickedId },
        success: function (data) {
            alert(data.message);
        },
        error: function () {
            alert("EmptyResult returns.");
            debugger;
            //var a = document.createElement('a');
            @*var hrefUri = '@Html.ActionLink("Delete2", "Customers")';*@
            @*var href = '@Html.ActionLink("Delete2", "Customers")/' + clickedId;*@
            window.location.href = @*'@Html.ActionLink("Delete2", "Customers")/' + clickedId;*@
                '@Url.Action("Delete2", "Customers")/' + clickedId;
            //a.click();
        },
        async: false
    });
    return false;
});
</script>

When I executed your code, I got a A potentially dangerous Request.Path value was detected from the client (<). error. The < is from the anchor. Could you please kindly clarify this part? - You used page controller as rest api controller, not a bad thing at all but do not mix thing around because maybe someone may work on your code. Is it something about post? Thanks a lot.

当我执行你的代码时,我从客户端(<)检测到一个潜在危险的Request.Path值。错误。 <来自锚。请你澄清这部分吗? - 你使用页面控制器作为rest api控制器,根本不是坏事,但不要混淆,因为可能有人可能会处理你的代码。是关于帖子的吗?非常感谢。< p>

#1


1  

error: function () {
            alert("EmptyResult returns.");
            debugger;
            $.post('@Url.Action("Delete2", "Customers")', { id: clickedId });
        },

Result of a post does not refresh your page, so quick fix is to genrate an anchor with URL to controller action add id parameter and click on it or change window location with controller/action/clicked id.

帖子的结果不刷新您的页面,因此快速修复是使用URL生成锚点到控制器操作添加id参数并单击它或使用controller / action / clicked id更改窗口位置。

error: function () {
                alert("EmptyResult returns.");
                debugger;
                var a = document.createElement('a');
                // something like, not sure :)
                var hrefUri = '@Html.ActionLink("Delete2", "Customers"'); 
                a.href = hrefUri + "/" + clickedId;
                a.click();
}

You used page controller as rest api controller, not a bad thing at all but do not mix thing around because maybe someone may work on your code. Usually posting stuff via ajax you expect a JSON result, in a ajax post/get request if you return a view + model you need to update somehow the page.

你使用页面控制器作为rest api控制器,根本不是坏事,但不要混淆,因为也许有人可能会处理你的代码。通常通过ajax发布你想要JSON结果的东西,在ajax post / get请求中如果你返回一个view + model你需要以某种方式更新页面。

#2


1  

@SilentTremor Thank you so much sir. You helped me to solve the problem. The working function is (ignore all the comments):

@SilentTremor先生,非常感谢你。你帮助我解决了这个问题。工作函数是(忽略所有注释):

<script type="text/javascript">
    $('.mergo-actionlink-delete').click(
function () {
    var clickedId = $(this).attr('data-value');
    $.ajax({
        dataType: "json",
        url: '@Url.Action("Delete", "Customers")',
        data: { id: clickedId },
        success: function (data) {
            alert(data.message);
        },
        error: function () {
            alert("EmptyResult returns.");
            debugger;
            //var a = document.createElement('a');
            @*var hrefUri = '@Html.ActionLink("Delete2", "Customers")';*@
            @*var href = '@Html.ActionLink("Delete2", "Customers")/' + clickedId;*@
            window.location.href = @*'@Html.ActionLink("Delete2", "Customers")/' + clickedId;*@
                '@Url.Action("Delete2", "Customers")/' + clickedId;
            //a.click();
        },
        async: false
    });
    return false;
});
</script>

When I executed your code, I got a A potentially dangerous Request.Path value was detected from the client (<). error. The < is from the anchor. Could you please kindly clarify this part? - You used page controller as rest api controller, not a bad thing at all but do not mix thing around because maybe someone may work on your code. Is it something about post? Thanks a lot.

当我执行你的代码时,我从客户端(<)检测到一个潜在危险的Request.Path值。错误。 <来自锚。请你澄清这部分吗? - 你使用页面控制器作为rest api控制器,根本不是坏事,但不要混淆,因为可能有人可能会处理你的代码。是关于帖子的吗?非常感谢。< p>