前言
这里记录MVC开发学习过程中遇到的各种问题,难度不一,类型不一,统统记录与此,方便以后整理归纳。
疑难杂症
以下各节已定义,但尚未为布局页“~/Views/Shared/_Layout.cshtml”呈现:“Scripts”。
原因不明,解决方法如下,待以后再分析。
<section>
@RenderBody()
</section>
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
Cannot attach the file ‘xxx.mdf’ as database ‘xxx’.
这个是擅自删除.mdf数据库文件所导致,因为这样删除,IDE会认为数据库丢失,而不是被正常删除,因此不会重建数据库。
解决方法就是删除并重启localdb,先打开程序包管理控制台。
sqllocaldb stop
sqllocaldb delete
sqllocaldb start
数据库没有正确记录数据
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace MvcDemo.Models {
//数据结构
public class Movie {
[Key]
public int Id { get; set; }
[Required]
[DisplayName("电影名")]
public string Title { get; set; }
[DisplayName("价格")]
[DataType(DataType.Currency)]
public double Price { get; set; }
}
}
上面数据结构中的价格,实际中无论在网页输入任何数值,数据库都只会记录默认值0
原因可能和controller当中的Bind()有关
解决方法:
原Controller中相关代码如下:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Title,Director,Content,Date")] Movie movie) {
if (ModelState.IsValid) {
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
精简为
[HttpPost]
public ActionResult Create(Movie movie) {
if (ModelState.IsValid) {
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
The database cannot be opened because it is version 869. This server supports version 852 and earlier. A downgrade path is not supported.
两台电脑同时做一个项目,vs版本都一样vs2017,其中一台曾经安装过vs2019,但是后面就删了重装2017,今天在装过2019的电脑上打开过这个项目一切正常,回来在另外一台电脑上面,就出现了这个错误。
看提示是版本数据库版本过低,于是我通过最新的SQL Server Express安装了localDB,但问题依然没有解决,绝望之际,怒删数据库,准备重做,没想到居然就好了,而且数据也没有丢失,遂记录下过程,以待有缘人。。。。
方法很简单,打开VS的程序包管理控制台
sqllocaldb stop
sqllocaldb delete
sqllocaldb start
Attribute
下面几种方式等同
//1
[HttpPost]
public ActionResult Delete(int id) {
}
//2
[HttpPost, ActionName("Delete")]
public ActionResult Whoisyourdaddy(int id) {
}
//3
[HttpPost]
[ActionName("Delete")]
public ActionResult Whoisyourdaddy(int id) {
}