奇怪的是,Visual Studio调试通过操作来查看,但没有任何内容返回浏览器

时间:2015-06-15 13:36:39

标签: c# jquery ajax asp.net-mvc razor

我遇到了一个非常奇怪的问题。 基本上,有一个Delete ActionLink。单击后,代码将检查条件,检查true / false,保留在当前页面或转到Delete view

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

无论如何,这是代码

索引视图:AJAX调用Delete action,返回JSON或EmptyResult。如果是EmptyResult,那么由于原始ActionLink已被禁用而失败,AJAX将调用error函数,该函数调用另一个action "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>

控制器:

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>

我对这些操作有Delete.cshtmlDelete2.cshtml次观看。症状是 - 从调试开始,Visual Studio进入Delete2操作,将“客户”返回到Delete2.cshtml视图,从头到脚执行。但浏览器仍停留在索引页面上。我认为AJAX中的return false;出了问题。我是新手,所以我需要一些帮助。感谢。

2 个答案:

答案 0 :(得分: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.

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.

答案 1 :(得分:1)

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

window.fbAsyncInit = function() {

    FB.init({
        appId      : 1234567890,
        xfbml      : true,
        version    : 'v2.3'
    });

    // Find the container that spans your entire content
    var contentWrapper = document.getElementById("content-wrapper");

    // Calculate element height using different methods because some browsers might calculate the height differently, then choose the highest
    var contentHeight = Math.max(wrapper.scrollHeight, wrapper.offsetHeight, wrapper.clientHeight);

    // Set canvas size
    FB.Canvas.setSize({ width: 810, height: contentHeight});

};

当我执行您的代码时,出现<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> 错误。 &lt;来自锚。请你澄清一下这部分吗? - A potentially dangerous Request.Path value was detected from the client (<).这是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.的问题吗?非常感谢。