[英]Asp.net MVC binding to view model
现状:从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; }
}
}
视图模型:
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>
我发现很多文章都在谈论模型绑定,但他们只讨论表单和输入。 我想要的是显示一些数据,例如从某种类型的列表中的数据库中显示,因此不需要向网站发布任何日期。
有没有人在我的示例代码中看到(可能是显而易见的)问题?
该项目基于使用DNX的 ASP.net 5 MVC 6 。
我已经设置了一些断点来查看控制器是否实际被调用。 它是。 我使用调试器的几个方法没有任何问题。 此外,输出窗口不显示任何错误或某事。 像那样。
GET方法的结果中缺少视图名称。 而不是
return View(new SampleViewModel());
一定是
return View("Sample", new SampleViewModel());
我认为视图和控制器之间的连接纯粹是基于约定的。 因此,一个控制器名为Sample
名为视图搜索Sample
在一个文件夹,名为Sample
这又是一个子文件夹Views
。
不确定为什么,但它以这种方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.