2010-07-30 75 views
0

見下文:有人可以解釋這個Linq-To-Sql代碼有什麼問題嗎?

Edit.aspx查看:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Test.Models.Friend>" %> 

編輯

<h2>Edit</h2> 

<% using (Html.BeginForm()) {%> 
    <%= Html.ValidationSummary(true) %> 

    <fieldset> 
     <legend>Fields</legend> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.Id) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.TextBoxFor(model => model.Id) %> 
      <%= Html.ValidationMessageFor(model => model.Id) %> 
     </div> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.Name) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.TextBoxFor(model => model.Name) %> 
      <%= Html.ValidationMessageFor(model => model.Name) %> 
     </div> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.Link) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.TextBoxFor(model => model.Link) %> 
      <%= Html.ValidationMessageFor(model => model.Link) %> 
     </div> 

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

<% } %> 

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

控制器編輯:

[Authorize(Roles = "Administrator")] 
    public ActionResult Edit(int id) 
    { 
     var eddy = friendsDB.Friends.Single(a => a.Id == id); 
     return View(eddy); 
    } 
    [HttpPost] 
    public ActionResult Edit(int id, string confirmButton) 
    { 
     var eddx = friendsDB.Friends.Single(a => a.Id == id); 
     try 
     { 
      UpdateModel(eddx, "Friend"); 
      friendsDB.SubmitChanges(); 
      return RedirectToAction("Index"); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 

不更新,所以它不是一個令人耳目一新的看法。 它通過議案,並返回到應該發生的「索引」,但該記錄保持未經編輯。任何想法或替代編輯與LINQ到SQL?謝謝。

+0

澄清是顯示未更新還是數據庫中的實際記錄未更新? – Ahmad 2010-07-30 06:06:02

回答

0

嘗試改變

var eddx = friendsDB.Friends.Single(a => a.Id == id); 

var eddx = friendsDB.Friends.GetById(id); 
0

或者嘗試改變

var eddx = friendsDB.Friends.Single(a => a.Id == id); 

var eddx = (from q in friendsDB.Friends 
    where q.Id == id 
    select q).SingleOrDefault(); 

或(未經測試...)

var eddx = friendsDB.Friends.Where(a => a.Id == id).Single(); 
0

您需要告知RedirectToAction("Index");您想要查看更新後的記錄。所以也許RedirectToAction("Index", new {id = eddx.Id});是你在找什麼。

+0

第二個問題是它沒有編輯。不是視圖不能更新。 – matiszac 2010-07-30 16:22:33

0

我認爲問題是你不綁定新對象,所以UpdateModel不知道從哪裏更新模型。

所以改變方法簽名:

public ActionResult Edit(int id, FormCollection values, string confirmButton) 

public ActionResult Edit(int id, Friend newfriend, string confirmButton) 

在第二個你可能會對朋友參數之前,需要[Bind(Prefix = "Friend")]如果朋友不在你的視圖模型,但只有模型的一部分。

相關問題