我是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: 我知道我大概可以得到它的工作原理是改變更新方法只需要一個參數,它是模型本身,但這不是我的項目中的一個選項。
我同意,但這不是我的選擇。那是否有其他方法可以使它工作? – yan 2013-02-27 17:17:18
我無法想象爲什麼不應該是一種選擇,你能詳細說明一下嗎? – Aviatrix 2013-02-27 21:36:45