2010-05-25 5 views
3

C# ASP.NET MVC 응용 프로그램에서 Link to SQL을 사용하여 응용 프로그램에 데이터를 제공합니다. 나는이 같은 간단한 데이터베이스 스키마를 가지고있다 : 이 같은 (당신이 등록 정보에서 그림의 오른쪽에 볼 수) Model라는이 데이터 컨텍스트 참조 내 컨트롤러 클래스에서 My database http://www.freeimagehosting.net/uploads/756d306565.jpgDataContext에 SubmitChanges를 호출해도 데이터베이스가 업데이트되지 않습니다.

:

private Model model = new Model(); 

을 내 페이지에 렌더링 된 시리즈의 목록 (목록)이 있습니다. 그것은 제대로 렌더링하고 나는이 같은 시리즈를 삭제하려면 삭제 기능을 추가 할 수 있었다 :

적절한 조치 링크는 다음과 같습니다
public ActionResult Delete(int id) { 
    model.Series.DeleteOnSubmit(model.Series.SingleOrDefault(s => s.ID == id)); 
    model.SubmitChanges(); 
    return RedirectToAction("Index"); 
} 

: 또한 생성 (비슷한 방식으로 구현)

<%: Html.ActionLink("Delete", "Delete", new { id=item.ID })%> 

잘 작동

. 그러나 편집이 작동하지 않습니다. 제 편집 내용은 다음과 같습니다.

public ActionResult Edit(int id) { 
    return View(model.Series.SingleOrDefault(s => s.ID == id)); 
} 

[HttpPost] 
public ActionResult Edit(Series series) { 

    if (ModelState.IsValid) { 
     UpdateModel(series); 

     series.Title = series.Title + " some string to ensure title has changed"; 
     model.SubmitChanges(); 

     return RedirectToAction("Index"); 
    } 
    return View(series); 
} 

데이터베이스에 기본 키가 올바르게 설정되어 있습니다. 내 응용 프로그램을 디버깅하고 model.SubmitChanges(); 줄 때까지 예상대로 모든 것을 발견했다. 이 명령은 데이터베이스에 대해 Title 등록 정보 (또는 다른 정보)의 변경 사항을 적용하지 않습니다.

도와주세요.

편집 : 내가이 줄을 추가하는 경우 : 변경이없는 model.Series.Attach(series); 단지 model.SubmitChanges(); 전에 - 편집이 아직 데이터베이스에 반영하지 않습니다. 매개 변수로 Edit 메서드에 전달 된 인스턴스는 이미 데이터 컨텍스트 model에 연결되어 있습니다.

편집 :보기 코드 방식의 편집에 속하는 :

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

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
Edit 
</asp:Content> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

<h2>Edit</h2> 

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

    <fieldset> 
     <legend>Fields</legend> 

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

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

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

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

<% } %> 

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

</asp:Content> 

답변

4

이것은 편집 작업의 모습입니다 (사용자 모드에 맞게 조정 됨). l) :

[HttpPost] 
public ActionResult Edit(int id, Series series) 
{ 
    Series updatingSeries = model.Series.Single(s => s.ID == id); 

    try 
    { 
     TryUpdateModel(updatingSeries); 
     model.SubmitChanges(); 

     return RedirectToAction("Details", new { id = updatingSeries.ID }); 
    } 
    catch 
    { 
     return View(updatingSeries); 
    } 
} 

경우에 따라 ModelState가 유효하지 않을 수 있기 때문에 발생할 수 있습니다. 보기로 뭔가 해봤 니? 또한보기 코드를 게시 할 수 있습니까?

+0

시리즈 매개 변수의 내용을 제어 메서드 (중단 점 사용)로 반환했기 때문에보기가 정상적으로 작동합니다. 모든 속성이 예상대로 설정되어보기가 정상적으로 작동합니다. 또한 아직 유효하지 않은 값으로 테스트하지 않기 때문에 ModelState.isValid()는 Edit 메서드 내에서 항상 true입니다. 어떤 비즈니스 규칙도 손상되지 않습니다. 어쨌든보기 코드를 추가 할 필요가 없습니다. – drasto

+0

보기 코드가 있습니다. 마지막 편집을 참조하십시오. – drasto

+0

내 코드를 대체하면 코드가 작동합니다. – drasto

1

첫째, 결코 지금이 당신이 Html.ActionLink("Delete", "Delete", new { id=item.ID })와 함께 일을하는지 정확히 무엇 (HTTP GET으로 "삭제"

.

편집의 경우 먼저 Attach의 인스턴스를 DataContext에 입력해야합니다.

+0

인스턴스가 이미 내 데이터 컨텍스트에 연결되어 있습니다. 편집을 참조하십시오. – drasto

+0

"삭제"에 관해서는, Html.ActionLink ("Delete", "Delete", 새로운 {id = item.ID}) 코드가 VS에 의해 생성되었습니다 ... – drasto

+0

@Anton : 왜 안 되죠? 그는 다른보기로 요청을 보낸 다음 HTTP POST를 통해 확인해야 할 수 있습니다. –

관련 문제