Asp.NET MVC3错误请求

时间:2012-12-03 04:29:20

标签: asp.net-mvc session session-variables

这是我在ASP.NET MVC(MVC3)中的第一个项目,我在处理所有事情时遇到了很多麻烦。根据所选语言,将从数据库中选择页面中的所有文本。对于这种语言选择,我更喜欢使用Session变量。我需要一个图像链接语言,所以我在.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>
}

HomeController

    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 - 错误请求”。谁能告诉我我做错了什么,或者我应该做些什么?

P.S。:我也试过没有Form,在Controller中添加一个名为 Lang 的新函数,并从那里重定向到Index,但没有成功。

3 个答案:

答案 0 :(得分:1)

您似乎正在混合使用Razor和WebForms语法。当你&#34;查看来源&#34;在您的网页上,我相信您的锚点中找不到正确的网址:

<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动词都将映射到此操作。

答案 1 :(得分:-1)

如果我没错,你的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中指定Controller时,它应该只是主页而不是 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>
}

请告诉我这是否适合您,或者您需要更多说明。感谢

答案 2 :(得分:-1)

我认为错误的原因可能是URL,请查看Scott Hanselman撰写的这篇文章 [http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx],它可能会让您了解如何使用URL中的特殊字符