2013-02-27 66 views
1

我是MVC的新手,目前在我的web項目中使用MVC 4 + EF Code First和WCF。基本上,在我的項目中,WCF服務將爲我從數據庫獲取數據,並且它也會處理更新數據。因此,當我完成更新記錄時,除了「傳統」MVC方式之外,我必須致電服務客戶端對我進行更改。下面是我的示例代碼:使用WCF在MVC 4中自定義更新方法

型號:

[DataContract] 
public class Person 
{ 
    [Key] 
    [DataMember] 
    public int ID{ get; set; } 

    [DataMember] 
    public string Name{ get; set; } 

    [DataMember] 
    public string Gender{ get; set; } 

    [DataMember] 
    public DateTime Birthday{ get; set; } 
} 

控制器:

[HttpPost] 
    public ActionResult Detail(int ID, string name, string gender, DateTime birthday) 
    { 
     // get the WCF proxy 
     var personClient = personProxy.GetpersonSvcClient(); 

     //update the info for a person based on ID, return true or false 
     var result = personClient.Updateperson(ID, name, gender, birthday); 

     if (result) 
     { 
      return RedirectToAction("Index"); 
     } 
     else 
     { 
      //if failed, stay in the detail page of the person 
      return View(); 
     } 
    } 

查看:

@model Domain.person 

@{ 
    ViewBag.Title = "Detail"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<h2>Detail</h2> 
@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 

<fieldset> 
    <legend>Person</legend> 

    @Html.HiddenFor(model => model.ID) 

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

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Gender) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Gender) 
     @Html.ValidationMessageFor(model => model.Gender) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Birthday) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Birthday) 
     @Html.ValidationMessageFor(model => model.Birthday) 
    </div> 
    <p> 
     <input type="submit" value="Update"/> 
    </p> 
</fieldset> 

} 

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

控制器是我感到困惑的部分。 Detail函數需要多個參數,我怎樣才能從View中調用它?另外,我應該投入到這個領域的收益在控制器:

//if failed, stay in the detail page of the person 
return View(); 

我們通常把模型,但模型似乎沒有改變,因爲我直接從我的WCF服務更新數據庫。

任何建議將非常感謝!

UPDATE: 我知道我大概可以得到它的工作原理是改變更新方法只需要一個參數,它是模型本身,但這不是我的項目中的一個選項。

回答

0

調用控制器中的細節動作,當你點擊「更新」

//旁註:使用單參數的函數,它接受它使生活更輕鬆

+0

我同意,但這不是我的選擇。那是否有其他方法可以使它工作? – yan 2013-02-27 17:17:18

+0

我無法想象爲什麼不應該是一種選擇,你能詳細說明一下嗎? – Aviatrix 2013-02-27 21:36:45

0

的形式將調用後的值方法在控制器中具有與提交時呈現視圖的get方法相同的名稱。

您可以通過在BeginForm方法

@using (Html.BeginForm("SomeAction", "SomeController")) 

此外,您使用的是強類型的視圖(好!)指定的參數,這樣你就可以改變你的POST方法的簽名接受改變這種默認行爲模型對象

[HttpPost] 
public ActionResult Detail(Person person) 
+0

謝謝你的回覆。我忘了提及我的post方法與get方法具有相同的名稱,只是有更多的參數。另外,正如我在我的文章的最新更新中提到的,公共ActionResult細節(人員)不是一個選項。我遇到的問題是我的post方法需要多個參數,我不知道如何從視圖中傳遞這些參數。 – yan 2013-02-27 17:07:12