1

我是 MVC 的新手,目前在我的 Web 项目中使用 MVC 4 + EF Code First 和 WCF。基本上,在我的项目中,WCF 服务会为我从数据库中获取数据,它也会负责更新数据。结果,当我完成更新记录时,我必须调用服务客户端来为我进行更改,而不是“传统”MVC 方式。这是我的示例代码:

模型:

[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 服务更新数据库。

任何建议将不胜感激!

更新: 我知道我可以通过将更新方法更改为仅采用模型本身的一个参数来使其工作,但这不是我的项目中的一个选项。

4

2 回答 2

0

表单将调用控制器中的 post 方法,该方法与提交时呈现视图的 get 方法同名。

BeginForm您可以通过在方法中指定参数来更改此默认行为

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

此外,您使用的是强类型视图(很好!),因此您可以更改 post 方法的签名以接受模型对象

 [HttpPost]
 public ActionResult Detail(Person person)
于 2013-02-27T16:56:38.663 回答
0

当您点击“更新”时,您在控制器中调用详细信息操作

//旁注:在你的函数中使用单个参数来接受它使生活更轻松的值

于 2013-02-27T16:44:04.253 回答