刚学不久,自己写一个小项目,出现了这个异常
不知道是不是Session["UserId"]引起的
上网搜到一些解决方法试了试还是不成功
想请大家帮忙看一看
Controller下的ActionResult
//Update Picture
[HttpPost]
public ActionResult UpdatePicture(PictureVM obj)
{
int userId = Convert.ToInt32(Session["UserId"]);
if (userId == 0)
{
return RedirectToAction("Login", "Account");
}
var file = obj.Picture;
User u = db.Users.Find(userId);
if( file != null)
{
//update the img
var extension = Path.GetExtension(file.FileName);
string id_and_extension = userId + extension;
string imgUrl = "~/Profile_Images/" + id_and_extension;
u.ImageUrl = imgUrl;
db.Entry(u).State = EntityState.Modified; //*
db.SaveChanges();
var path = Server.MapPath("~/Profile_Images/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path + id_and_extension);
}
//when update new img, delete old img
if ((System.IO.File.Exists(path + id_and_extension))) //imgUrl
{
System.IO.File.Delete(path + id_and_extension);
}
file.SaveAs((path + id_and_extension));
}
return RedirectToAction("UserProfile");
}
UserProfile.cshtml下关于ImageUrl的部分
<dt>
@Html.DisplayNameFor(model => model.ImageUrl)
</dt>
<dd style="margin-top:15px">
@*@if(Model.ImageUrl.Length > 0)*@
@*System.NullReferenceException: '未将对象引用设置到对象的实例。'
ClairG.ChatApp.Domain.Entities.User.ImageUrl.get returned null.*@
@if (Model.ImageUrl != null) //无法保存图片
{
<img src="@Url.Content(Model.ImageUrl)" alt="No Image" style="height:200px" class="img-responsive img-circle" />
}
<br /><br />
@using (Html.BeginForm("UpdatePicture", "User", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<input type="file" name="Picture class=" col-sm-2 form-control"" />
<input type="submit" value="Save Image" class="btn btn-default" />
}
</dd>