c# – Asp.net MVC绑定到查看模型
发布时间:2020-12-15 20:59:52 所属栏目:百科 来源:网络整理
导读:现状:从ASP.net MVC开发开始,来自MVVM应用程序开发我正在努力将视图绑定到视图模型/控制器.我从一个空项目开始,尝试创建模型,视图模型,控制器和视图.启动项目我得到一个“500内部服务器错误”,但不明白什么是错误的(输出窗口中没有错误).我只是无法理解视图
现状:从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的子文件夹. 不确定为什么,但它以这种方式工作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |