简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM