当前情况:我开始学习ASP.net MVC开发,之前从事MVVM应用程序开发,我在试图将视图与视图模型/控制器绑定时遇到了困难。我从一个空项目开始尝试创建模型、视图模型、控制器和视图。启动项目后,我遇到了“500内部服务器错误”,但不知道出了什么问题(输出窗口没有错误信息)。我无法理解视图实际上如何绑定到视图模型(可能是因为我太过于深入地思考了MVVM)。
我目前拥有的:
Startup.cs:
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace WebApplication1
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Sample}/{action=Index}/{id?}");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
模型:
using System;
namespace WebApplication1.Models
{
public class SomeModel
{
public string Title { get; set; }
public DateTime Time { get; set; }
}
}
ViewModel:
using System;
using System.Collections.Generic;
using WebApplication1.Models;
namespace WebApplication1.ViewModels
{
public class SampleViewModel
{
public IList<SomeModel> SomeModels { get; set; }
public SampleViewModel()
{
SomeModels = new List<SomeModel>();
SomeModels.Add(new SomeModel()
{
Time = DateTime.Now,
Title = "Hallo"
});
}
}
}
控制器:
using Microsoft.AspNet.Mvc;
using WebApplication1.ViewModels;
namespace WebApplication1.Controllers
{
public class SampleController : Controller
{
//
// GET: /Sample/
public IActionResult Index()
{
return View(new SampleViewModel());
}
}
}
查看:
@model WebApplication1.ViewModels.SampleViewModel
<!DOCTYPE html>
<html>
<head>
<title>Hallo</title>
</head>
<body>
@foreach (var someModel in Model.SomeModels)
{
<div>@someModel.Title</div>
}
</body>
</html>
我发现很多文章都在谈论模型绑定,但它们只涉及表格和输入。我想要展示一些数据,例如从数据库中获取的数据列表,因此不需要向网站提交任何数据。
有人看到我的示例代码中(可能显而易见的)问题了吗?
该项目基于ASP.net 5 MVC 6使用DNX。
我已经设置了一些断点来查看控制器是否被调用。而且确实是被调用了。我通过调试器仔细检查了几个方法,没有发现任何问题。另外,输出窗口也没有显示任何错误。
Index()
处设置一个断点,你应该能找到错误发生的地方。也许你甚至没有触发控制器。 - Alexander Derck