Asp.NET MVC3 错误请求



这是我在MVC (MVC3 ASP.NET 的第一个项目,我在处理所有事情时遇到了很多麻烦。根据所选语言,我将从数据库中选择页面中的所有文本。对于此语言选择,我更喜欢使用会话变量。我需要语言的图像链接,所以我将以下行写入 .cshtml 页面。

@using (Html.BeginForm()) {
    <a href='<%: Url.Action("Index", "Home", new { lang="Tr" }) %>'>
        <img src="../../Content/Images/flag_tr.jpg" width="40" height="20" />
    </a>
    <a href='<%: Url.Action("Index", "Home", new { lang = "En" }) %>'>
        <img src="../../Content/Images/flag_en.jpg" width="40" height="20" />
    </a>
}

家庭控制器中:

    public ActionResult Index()
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        ViewBag.Selected = "Not yet selected";
        return View();
    }
    [HttpPost]
    public ActionResult Index(String lang)
    {
        if (lang == "Tr")
        {
            System.Web.HttpContext.Current.Session["Language"] = "Tr";
        }
        else if (lang == "En")
        {
            System.Web.HttpContext.Current.Session["Language"] = "En";
        }
        ViewBag.Selected = System.Web.HttpContext.Current.Session["Language"];
        return View();
    }

当我单击标志链接时,我收到"HTTP 错误 400 - 错误请求"。谁能告诉我我做错了什么,或者我应该做什么?

PS:我也尝试过没有表单,在控制器中添加一个名为 Lang 的新功能并从那里重定向到 Index,但没有成功。

您似乎混合了 Razor 和 WebForms 语法。当您在页面上"查看源代码"时,我相信您不会在锚点中看到正确的 URL:

<a href='<%: Url.Action("Index", "Home", new { lang="Tr" }) %>'>

应该是:

<a href='@Url.Action("Index", "Home", new { lang="Tr" })'>

另外,请注意,锚点会导致 HTTPGET,即使是在表单中,因此您需要使用 JavaScript 覆盖它们的行为,或者将lang检查添加到控制器操作的 HTTPGET 版本中。 尝试这样的事情,将两个控制器操作合并为一个:

public ActionResult Index(string lang)
{
    if (lang == "Tr")
    {
        System.Web.HttpContext.Current.Session["Language"] = "Tr";
    }
    else if (lang == "En")
    {
        System.Web.HttpContext.Current.Session["Language"] = "En";
    }
    ViewBag.Message = "Welcome to ASP.NET MVC!";
    ViewBag.Selected = System.Web.HttpContext.Current.Session["Language"] ?? "Not yet selected";
    return View();
}

如果不使用 [HttpGet][HttpPost] 来修饰它,则任何 HTTP 谓词都将映射到此操作。

如果我没记错的话,你的HomeController类名是HomeController

<a href='<%: Url.Action("Index", "HomeController", new { lang="Tr" }) %>'>
    <img src="../../Content/Images/flag_tr.jpg" width="40" height="20" />
</a>

因此,当您在 Url.Action 中指定控制器时,它应该只是 Home,而不是 HomeController

因此,视图中的代码将如下所示:

@using (Html.BeginForm()) {
    <a href='<%: Url.Action("Index", "Home", new { lang="Tr" }) %>'>
        <img src="../../Content/Images/flag_tr.jpg" width="40" height="20" />
    </a>
    <a href='<%: Url.Action("Index", "Home", new { lang = "En" }) %>'>
        <img src="../../Content/Images/flag_en.jpg" width="40" height="20" />
    </a>
}

让我知道这是否适合您,或者您需要更多澄清。谢谢

相关内容

最新更新