以下の記事のような複合型のモデルバインディングをしたいのだと想像していますが、いかがですか?
コレクションのデータアノテーション検証
http://surferonwww.info/BlogEngine/post/2014/09/01/validation-of-collection-data-during-model-binding-using-data-annotation.aspx
Country と CountryInfo という 2 つのクラスのコレクションを ListCountriesViewModel クラスにまとめて、ListCountriesViewModel クラスを View に型付けているところを見てください。
今回の質問者さんのケースはコレクションではなさそうですが、この記事の応用で行けると思います。
これがやりやいことと違う場合はその旨連絡ください。
その際は、先にお願いしたように、やりたいことや質問の背景&全体のシナリオ・ストーリーをきちんと書いてください。
----- 2017/6/25 13:03 追記 -----
上の紹介した記事は例としては好ましくなかったです。すみませんが忘れてください。代わりに以下に別の例を書いておきます。
html の input type="text" 要素を使っても name 属性の設定が適切ならモデルバインディングは問題ありませんが、以下の問題があるので Html ヘルパーを使うことをお勧めします。
(1) データアノテーション検証でクライアント側での検証ができない(サーバー側は検証されますが)。
(2) クライアント側での検証が不要ということであっても、サーバー側で検証 NG の場合、下の Controller のコードのように return View(z) としたいはずですが、それができない。
Model
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Mvc4App.Models
{
public class A
{
[Required(ErrorMessage="param1 は必須")]
public string param1 { set; get; }
}
public class B
{
[Required(ErrorMessage = "param2 は必須")]
public string param2 { set; get; }
[Required(ErrorMessage = "param3 は必須")]
public string param3 { set; get; }
}
public class Z
{
[Required(ErrorMessage = "Title は必須")]
public string Title { set; get; }
public A A_Class { set; get; }
public B B_Class { set; get; }
}
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc4App.Models;
namespace Mvc4App.Controllers
{
public class ParentChildController : Controller
[HttpGet]
public ActionResult Create3()
{
return View();
}
[HttpPost]
public ActionResult Create3(Z z, A a_class, B b_class)
{
if (!ModelState.IsValid)
{
return View(z);
}
return RedirectToAction("Index", "Home");
}
}
}
View
@model Mvc4App.Models.Z
@{
ViewBag.Title = "Create3";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create3</h2>
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Title)
@Html.EditorFor(m => m.Title)
@Html.ValidationMessageFor(m => m.Title)
<hr />
@Html.LabelFor(m => m.A_Class.param1)
@Html.EditorFor(m => m.A_Class.param1)
@Html.ValidationMessageFor(m => m.A_Class.param1)
<hr />
@Html.LabelFor(m => m.B_Class.param2)
@Html.EditorFor(m => m.B_Class.param2)
@Html.ValidationMessageFor(m => m.B_Class.param2)
@Html.LabelFor(m => m.B_Class.param3)
@Html.EditorFor(m => m.B_Class.param3)
@Html.ValidationMessageFor(m => m.B_Class.param3)
<hr />
<input type="submit" value="POST" />
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
2017/6/25 13:03 追記がやりやいことと違う場合はその旨連絡ください。
その際は、先にお願いしたように、やりたいことや質問の背景&全体のシナリオ・ストーリーをきちんと書いてください。