0

我讨厌违反 DRY 规则。

对于 url:/student/charles /Views/Student/Show.cshtml 将使用学生模型呈现。

如何使用 asp.net mvc 实现它?

(我可以从 URL 获取相关模型)

我想我已经解决了。我正在通过此代码捕获所有请求:

  routes.MapRoute("CatchAll", "{*url}",
            new { controller = "Base", action = "Dispatch" }
        );

现在我正在尝试在调度程序中调用 CustomView。

瞧:

 public class BaseController : Controller
{

    public ActionResult Dispatch(string url)
    {
        object model = null;
        .....
        return View("~/Views/Student/Show.cshtml", model);

    }
}     

看起来很脏但很有效:) 我愿意接受任何更好的实施。

4

1 回答 1

2

我承认我不确定您要完成什么。我首先不明白如果您以正常的 MVC 方式实现它,您将如何违反 DRY。

你会做这样的事情。

模型:Student.cs

public class Student {
  public string StudentId { get; set; }
  public string Name { get; set; }
}

控制器:StudentController.cs

public class StudentController : Controller {

  public ActionResult Student(string id) {
    // TODO: Get the student by ID and return the view displaying the student.
    return View(student);
  }
}

视图:Student.cshtml - 为学生模型(或视图模型)创建一个强类型视图。

很简单也很直接。您不需要弄乱路由(我不建议您不要全部捕获 - 我什至不确定这会给您带来什么)。当然,如果您想获取 URL/Student/StudentName,则需要稍微处理一下路由,但这也很简单。

同样,我只是在说明基本的 MVC 设置。我不确定您要保持 DRY 什么 - 我没有看到您重复代码的任何地方。也许你可以澄清一下?

于 2012-11-19T03:20:11.737 回答