The_Cthulhu_Kid
The_Cthulhu_Kid

Reputation: 1859

Inserting default values in "EditorForModel()"

In my application I have a view to manage addresses.

When the action is called it is passed IDs and a bool value. If true an address should be edited rather than created. Is there any way to assign the values from the address to be edited to the EditorForModels fields or is it better writing each field out individually?

 @Html.EditorForModel()

or

    <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"/>

Upvotes: 1

Views: 77

Answers (1)

Ant P
Ant P

Reputation: 25221

Use a strongly-typed view, assign values to properties of a Model object and pass this to your view. This will result in pre-populated editor templates:

Model:

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

Controller:

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

View:

@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>

Upvotes: 1

Related Questions