在“EditorForModel()”中插入默认值

时间:2013-04-14 14:32:45

标签: c# asp.net-mvc-3 editorformodel

在我的应用程序中,我有一个管理地址的视图。

当调用动作时,它会传递ID和bool值。如果为true,则应编辑地址而不是创建地址。有没有办法将要编辑的地址中的值分配给EditorForModels字段,还是更好地单独写出每个字段?

 @Html.EditorForModel()

    <input type="text" required="required" name="firstName" value="@fName"/>
    <br/>
    <label>Last Name: </label>
    <input type="text" required="required" name="lastName" value="@lName"/>
    <br/>
    <label>Address: </label>
    <input type="text" required="required" name="address" value="@addy"/>
    <br/>
    <label>Town: </label>
    <input type="text" required="required" name="town" value="@town"/>
    <br/>
    <label>Post Code: </label>
    <input type="text" required="required" name="postCode" value="@postCode"/>

1 个答案:

答案 0 :(得分:1)

使用强类型视图,为Model对象的属性赋值并将其传递给视图。这将导致预先填充的编辑器模板:

型号:

public class SomethingModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PostCode { get; set; }
}

控制器:

public ActionResult MyAction()
{
    var model = new SomethingModel {
        FirstName = "John",
        LastName = "Doe",
        PostCode = "XXY XXY"
    };
    return View(model);
}

查看:

@model SomethingModel

<div class="input">
    @Html.TextBoxFor(m => m.FirstName)
</div>
<div class="input">
    @Html.TextBoxFor(m => m.LastName)
</div>
<div class="input">
    @Html.TextBoxFor(m => m.PostCode)
</div>