【问题标题】:why can I not pass a parameter in the url directly to my method in MVC (the parameter is always null)为什么我不能将url中的参数直接传递给我在MVC中的方法(参数始终为null)
【发布时间】:2017-06-25 03:33:57
【问题描述】:

所以这些是 HomeController.cs 和 RouteConfig.cs。当我尝试编写 URL:localhost/Home/Index/Sometitle 时,该参数始终为空。当我编写 URL 时发生同样的事情:localhost/Home/Ajouter/SomeTitle。我已经尝试在互联网上找到答案,但没有成功。有人可以告诉我有什么问题或遗漏吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Wiki.Models.DAL;

namespace Wiki.Controllers
{
    public class HomeController : BaseController //Controller
    {
        Articles allArticles = new Articles();

        // GET: Home
        [HttpGet]
        public ActionResult Index(string title)
        {
            if (String.IsNullOrEmpty(title))
                return View();
            else
                return RedirectToAction("Index", "Article", new { title = title });
        }

        [HttpGet]
        public ActionResult Ajouter(string title)
        {
            if (ModelState.IsValid)
                return RedirectToAction("Edit", "Article", new { title = title });
            else
                return View("Index");
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Wiki
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //routes.MapRoute(
            //    name: "Wiki",
            //    url: "Wiki/{titre}/{action}",
            //    defaults: new { controller = "Wiki", action = "Index", titre = UrlParameter.Optional }
            //);

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

【问题讨论】:

  • 请显示 Post to Ajouter 的视图
  • 索引路由调用id,但你的参数调用title

标签: c# asp.net-mvc routes url-parameters


【解决方案1】:

您需要将参数名称更改为Id:

public ActionResult Index(string Id)

或者用这个替换路由:

routes.MapRoute(
            name: "CustomName",
            url: "{controller}/{action}/{title}",
            defaults: new { controller = "Home", action = "Index", title = UrlParameter.Optional }
        );

我真正推荐的是阅读更多关于 MVC 中的路由

【讨论】:

    【解决方案2】:

    你的路由必须匹配控制器变量名试试这个。

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{title}",
            defaults: new { controller = "Home", action = "Index", title = UrlParameter.Optional }
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      相关资源
      最近更新 更多