简体   繁体   中英

why can I not pass a parameter in the url directly to my method in MVC (the parameter is always null)

So these are the HomeController.cs and RouteConfig.cs. When I tried to write the URL : localhost/Home/Index/Sometitle, the parameter is always null. The same thing happen when I wrote the URL : localhost/Home/Ajouter/SomeTitle. I already tried to find on the internet an answer but I had no success. Can someone tell me what's wrong or missing?

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 }
            );
        }
    }
}

You need to change your parameter name to Id:

public ActionResult Index(string Id)

or replace the route with this:

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

What I really recommand is to read more about routing in MVC

Your route must match the controller variable name try this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM