Friendly URLs for ASP.NET

后端 未结 6 1094
旧时难觅i
旧时难觅i 2020-11-30 19:48

Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example http://somewhere.overtherainbow.com/userid/12342

6条回答
  •  执念已碎
    2020-11-30 20:28

    Here's another way of doing it using ASP.NET MVC

    First off, here's the controller code with two actions. Index gets a list of users from the model, userid gets an individual user:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    
    namespace MvcApplication1.Controllers
    {
        public class UsersController : Controller
        {
            public ActionResult Index()
            {
                return View(Models.UserDB.GetUsers());
            }
            public ActionResult userid(int id)
            {
                return View(Models.UserDB.GetUser(id));
            }
        }
    }
    

    Here's the Index.asp view, it uses an ActionLink to create links in the correct format:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Index" %>
    <%@ Import Namespace="MvcApplication1.Controllers" %>
    <%@ Import Namespace="MvcApplication1.Models" %>
    
    
    
    
    
        
    
    
        

    Index of Users

      <% foreach (User user in (IEnumerable)ViewData.Model) { %>
    • <%= Html.ActionLink(user.name, "userid", new {id = user.id })%>
    • <% } %>

    And here's the userid.aspx view which displays an individual's details:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="userid.aspx.cs" Inherits="MvcApplication1.Views.Users.userid" %>
    <%@ Import Namespace="MvcApplication1.Controllers" %>
    <%@ Import Namespace="MvcApplication1.Models" %>
    
    
    
    
        
    
    
        
    ID <%=((User)ViewData.Model).id %>
    Name <%=((User)ViewData.Model).name %>

    And finally for completeness, here's the model code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace MvcApplication1.Models
    {
        public class UserDB
        {
            private static List users = new List{
                new User(){id=12345, name="Bill"},
                new User(){id=12346, name="Claire"},
                new User(){id=12347, name="David"}
            };
    
            public static List GetUsers()
            {
                return users;
            }
    
            public static User GetUser(int id)
            {
                return users.First(user => user.id == id);
            }
    
        }
    
        public class User
        {
            public int id { get; set; }
            public string name { get; set; }
        }
    }
    

提交回复
热议问题