Billdr
Billdr

Reputation: 1579

Creating a strongly typed view based on a custom model

I have need of a view that combines two entity models. I created a class that looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FSDS.DataModels;

namespace FSDS.WebUX.Models
{
    public partial class ChainandJob
    {
        public ScheduleJobChain chain {get;set;} //this object has 6 properties
        public ScheduleJob job {get;set;} //this object has 8 properties.
    }
}

I created a new partial view using the "create" scaffolding. This is what it gives me:

@model FSDS.WebUX.Models.ChainandJob

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ChainandJob</legend>

        <p>
             <input type="submit" value="Create" />
        </p>
    </fieldset>
 }

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

Where are all the fields?

Upvotes: 1

Views: 162

Answers (2)

Display Name
Display Name

Reputation: 4732

VS doesn't know your objects. Right after <legend>ChainandJob</legend> try adding

@EditorFor(m => m.chain.ChainProperty)
@ValidationMessageFor(m => m.chain.ChainProperty)

@EditorFor(m => m.job.JobProperty)
@ValidationMessageFor(m => m.job.JobProperty)

and things will be hunky dory :) EditorFor will generate the default output for you, should you need to tweak it - feel free to do so.

Upvotes: 2

Garrett Fogerlie
Garrett Fogerlie

Reputation: 4458

You will need to write it yourself, something like:

@Html.EditorFor(model => model.ChainandJob.chain.Bla)
@Html.ValidationMessageFor(model => model.ChainandJob.chain.Bla)
@Html.EditorFor(model => model.ChainandJob.job.Bla)
@Html.ValidationMessageFor(model => model.ChainandJob.job.Bla)

And so on.

Edit

Although I don't do it this way, you could have VS create a edit view for SchedualJobChain, and another one for ScheduleJob and cut the templates it creates into one for you view model. Don't forget the @Html.HiddenFor(model => model.ChainandJob.chain.Id etc.

Upvotes: 3

Related Questions