MVC 控制器被调用两次 [英] MVC controller is being called twice

查看:50
本文介绍了MVC 控制器被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它从 ActionLink 调用中被调用了两次.

I have a controller that is being called twice from an ActionLink call.

我的主页有一个链接,点击后会调用 Play 控制器上的 Index 方法.将 100 的 id 传递到该方法中.我认为这就是导致问题的原因.更多详情请见下文.

My home page has a link, that when clicked calls the Index method on the Play controller. An id of 100 is passed into the method. I think this is what is causing the issue. More on this below.

以下是一些代码片段:

主页:

<%= Html.ActionLink("Click Me", "Index", "Play", new { id = 100 }, null) %>

播放控制器:

public ActionResult Index(int? id)
{
    var settings = new Dictionary<string, string>();
    settings.Add("Id", id.ToString());
    ViewData["InitParams"] = settings.ToInitParams();
    return View();
}

播放视图:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

(html <head> omitted for brevity)

<body>
    <form id="form1" runat="server" style="height:100%">
        Hello
    </form>
</body>

如果我去掉 Index 方法的参数,一切都很好.如果我将参数保留在原处,则使用 100 作为 id 调用 Index 方法.返回 View 后,该方法被第二次调用,参数为 null.

If I get rid of the parameter to the Index method, everything is fine. If I leave the parameter in place, then the Index method is called with 100 as the id. After returning the View, the method is called a second time with a parameter of null.

我似乎无法弄清楚是什么触发了第二个调用.

I can’t seem to figure out what is triggering the second call.

我的第一个想法是添加这样的特定路线:

My first thought was to add a specific route like this:

routes.MapRoute(
    "Play", // Route name
    "Play/{id}", // URL with parameters
    new {controller = "Play", action = "Index"} // Parameter defaults
);

除了制作一个看起来更漂亮的链接之外,这没有任何效果.

This had no effect other than making a prettier looking link.

我不知道从哪里开始.

推荐答案

是否还有其他标记可能会意外引用该页面?脚本引用、图像引用、css 引用,都可能被错误地指向 '.'或当前页面.

Is there any other markup that could be accidentally referencing the page? Script references, image references, css references, all could be mistakenly pointed at '.' or the current page.

这篇关于MVC 控制器被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆