ASP.Net MVC 4更新值链接到外键列 [英] ASP.Net MVC 4 Update value linked to a foreign key column

查看:147
本文介绍了ASP.Net MVC 4更新值链接到外键列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,我对MVC 4和ASP.net都比较陌生。我试图用一些属性创建一个房间,其中一个查询来自另一个模型中包含的状态列表。我有我的课程设置如下:

Room.cs

  public class Room 
{
[Key]
public Guid RoomId {get;组; }
[必需(ErrorMessage =房间名称是必需的)]
public string Name {get;组; }
public string描述{get;组; }
public virtual Status Status {get;组; }
[DisplayName(Created On)]
public DateTime?创建{get;组; }
[DisplayName(Last Modified)]
public DateTime?修改{get;组; }
}

Status.cs

  public class Status 
{
[Key]
public int StatusId {get;组; }
public string Name {get;组; }
public string描述{get;组; }
}

当我使用默认脚手架使用下面的代码,这是完美的工作,并正确地应用新的状态到新创建的房间。

//发布:/房间/创建

  [HttpPost] 
[ValidateAntiForgeryToken]
public ActionResult Create(Room room)
{
if(ModelState.IsValid)
{
room.Created = DateTime.Now;
room.Status = db.Statuses.Single(s => s.Name ==New);
room.RoomId = Guid.NewGuid();
db.Rooms.Add(room);
db.SaveChanges();
返回RedirectToAction(Index);
}

return查看(room);





$ b

当我尝试使用相同的语法来指定编辑操作中的room.Status时,在我的情况下,自动将状态从新建更改为发现,状态值在数据库中从不修改。我跟踪当地人直到db.SaveChanges();电话,我可以看到房间的状态值正确地反映了新的状态的定义,但它不是在后端更新。这里是我的更新代码:

房间/编辑/ 5

$ $ p $ $ $ $ (房间空间)
{
if(ModelState.IsValid)

room.Modified)
[ValidateAntiForgeryToken]
public ActionResult = DateTime.Now;
room.Status = db.Statuses.Single(s => s.Name ==Discovery);
db.Entry(room).State = EntityState.Modified;
db.SaveChanges();
返回RedirectToAction(Index);
}
return View(room);
}

我不知道如何改变这个值!我的编辑视图如下:

  @model vwr.Cloud.Models.Room 

@ {
ViewBag.Title =编辑;
}

< h2>编辑< / h2>
$ b $ @(Html.BeginForm()){
@ Html.AntiForgeryToken()
@ Html.ValidationSummary(true)

< fieldset> ;
< legend>房间 - @ Html.ValueFor(model => model.Name)< / legend>

Html.HiddenFor(model => model.RoomId)
@ Html.HiddenFor(model => model.Name)
@ Html.HiddenFor(model => ; model.Created)
@ Html.HiddenFor(model => model.Status.StatusId)

< div class =editor-label>
房间状态 - @ Html.ValueFor(model => model.Status.Name)
< / div>
< div class =editor-label>
创建日期 - @ Html.ValueFor(model => model.Created)
< / div>
< div class =editor-label>
@ Html.LabelFor(model => model.Description)
< / div>
< div class =editor-field>
@ Html.EditorFor(model => model.Description)
@ Html.ValidationMessageFor(model => model.Description)
< / div>

< p>
< input type =submitvalue =Save/>
< / p>
< / fieldset>
}

< div>
@ Html.ActionLink(Back to List,Index)
< / div>


解决方案

但我也需要添加一个[ForeignKey]条目到我的房间类映射到导航属性。我不能说我还不明白它是如何工作的,可以这么说: - )。
$ b $ final final.cs

  public class Room 
{
[Key]
public Guid RoomId {get;组; }
[必需(ErrorMessage =房间名称是必需的)]
public string Name {get;组; }
public string描述{get;组; }

[ForeignKey(Status)]
public virtual int StatusId {get;组; }

public virtual Status Status {get;组; }
[DisplayName(Created On)]
public DateTime?创建{get;组; }
[DisplayName(Last Modified)]
public DateTime?修改{get;组; }
}


I'm relatively new to MVC 4 and ASP.net in general. I'm trying to create a "room" with some properties, one of which queries from a list of statuses contained in another model. I have my classes set up as follows:

Room.cs

public class Room
    {
        [Key]
        public Guid RoomId { get; set; }
        [Required(ErrorMessage = "A Room Name is required")]
        public string Name { get; set; }
        public string Description { get; set; }
        public virtual Status Status { get; set; }
        [DisplayName("Created On")]
        public DateTime? Created { get; set; }
        [DisplayName("Last Modified")]
        public DateTime? Modified { get; set; }
    }

Status.cs

public class Status
    {
        [Key]
        public int StatusId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

When I use the default scaffolding for the create action against the room, I am using the following code, which is working flawlessly, and properly applying the status of "New" to the newly created room.

// Post: /Room/Create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Room room)
        {
            if (ModelState.IsValid)
            {
                room.Created = DateTime.Now;
                room.Status = db.Statuses.Single(s => s.Name == "New");
                room.RoomId = Guid.NewGuid();
                db.Rooms.Add(room);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(room);
        }

When I attempt the same syntax for assigning room.Status on an edit action, in my case, automatically changing the status from "New" to "Discovery", the status values are never modified in the database. I am tracing the locals right up to the db.SaveChanges(); call, and I can see that the room.Status value is accurately reflecting the definition to the new status, but it's simply not updating on the back end. Here is my update code:

//Room/Edit/5

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Room room)
        {
            if (ModelState.IsValid)
            {
                room.Modified = DateTime.Now;
                room.Status = db.Statuses.Single(s => s.Name == "Discovery");
                db.Entry(room).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(room);
        }

I'm at a loss as to how to change this value! My Edit view is as follows:

@model vwr.Cloud.Models.Room

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Room - @Html.ValueFor(model => model.Name)</legend>

        @Html.HiddenFor(model => model.RoomId)
        @Html.HiddenFor(model => model.Name)
        @Html.HiddenFor(model => model.Created)
        @Html.HiddenFor(model => model.Status.StatusId)

        <div class="editor-label">
            Room Status - @Html.ValueFor(model => model.Status.Name)
        </div>
        <div class="editor-label">
            Created Date - @Html.ValueFor(model => model.Created)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

解决方案

It took me WAY too long to figure this out, but I also needed to add a [ForeignKey] entry to my Room class that mapped to the Navigation Property. I can't say I yet understand HOW it works, suffice to say, it does :-).

Final room.cs

public class Room
    {
        [Key]
        public Guid RoomId { get; set; }
        [Required(ErrorMessage = "A Room Name is required")]
        public string Name { get; set; }
        public string Description { get; set; }

        [ForeignKey("Status")]
        public virtual int StatusId { get; set; }

        public virtual Status Status { get; set; }
        [DisplayName("Created On")]
        public DateTime? Created { get; set; }
        [DisplayName("Last Modified")]
        public DateTime? Modified { get; set; }
    }

这篇关于ASP.Net MVC 4更新值链接到外键列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆