简体   繁体   English

有没有一种方法可以从ASP.NET MVC中的链接中删除ID

[英]Is there a way to remove ID from link in ASP.NET MVC

I am working on ASP.NET MVC project. 我正在研究ASP.NET MVC项目。 I am facing one problem now. 我现在面临一个问题。 I am redirecting from one action to other when I click on Add list option in my drop down. 单击下拉列表中的“ 添加列表”选项时,我正在从一种操作重定向到另一种操作。

This is the script I am using for redirection : 这是我用于重定向的脚本:

 $("#DrpList").change(function (e) {
     if ($(this).val() == 'Add List') {
         document.location.href = 'http://localhost:1234/report/Index/indexid'

Here indexid is just random id which I am passing and it is static, So I can compare this in my Index controller and display view I need. 这里的indexid只是我传递的随机id,它是静态的,因此我可以在Index控制器中比较它并显示所需的视图。

Here what I want is, after i pass indexid parameter to index, when Index page displays, I can see indexid in my link like this, 我想要的是,在将indexid参数传递给索引之后,当显示“索引”页面时,我可以在这样的链接中看到indexid,

http://localhost:1234/report/Index/indexid

but i just need to display, 但我只需要展示,

http://localhost:1234/report/Index 

I tried to do like : 我试图做到:

return view("Index", "report", new{id = ""});

But it doesn't work. 但这是行不通的。 So how can I achieve this ? 那么我该如何实现呢?

Update : 更新:

 public ActionResult Index(string id)
    {
  if (id == "indexid")
  {
  //Here Add items to list
 return View("Index", "report", new { id = "" });
  }

Your Report Controller Index action signature should use indexid and not default id . 您的“报表控制器索引”操作签名应使用indexid而不是default id Also indexid should be nullable 另外indexid应该可以为nullable

public class ReportController:Controller
{

   public ActionResult Index(string indexid)
   {

   }

}

and

 return view("Index", "report", new{indexid= ""});

You can use ActionFilter to route as per your requirement. 您可以根据需要使用ActionFilter进行路由。 Create an ActionFilter as shown below - 创建一个ActionFilter,如下所示-

public class MyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var rd = filterContext.RouteData;
        if(rd.Values.Keys.Contains("id"))
        {
            filterContext.HttpContext.Items["key"] = rd.Values["id"];
            rd.Values.Remove("id");
            filterContext.Result = new RedirectResult("/Controller/Index");
        }
    }
}

Then use this Filter on the action where you are passing ID as the value - 然后在您将ID作为值传递的操作上使用此过滤器-

    [MyFilter]
    public ActionResult Index()
    {
        return View();
    }

You can access id value in the Action using HttpContext.Items["id"] . 您可以使用HttpContext.Items["id"]在Action中访问id值。

When you request to a page with URL - /Controller/Action/indexid , it will be redirected to /Controller/Index 当您请求使用URL- /Controller/Action/indexid的页面时,该页面将被重定向到/Controller/Index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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