モデルにデータを入力し、そのモデルをビューからアクション メソッドに渡します。forループを表示して、モデルに基づいてラジオボタンを生成します。
このコードを見てください。ここでは、モデルに手動でデータを入力し、アクション メソッドからビューに渡します。
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var student = new StudentModel
{
FirstName = "Rion",
LastName = "Gomes",
//I think the best way to populate this list is to call a service here.
Sex = new List<Sex>
{
new Sex{ID="1" , Type = "Male"},
new Sex{ID="2" , Type = "Female"}
}
};
return View(student);
}
Sexプロパティに基づいて、ループ内のラジオボタンを生成しません.ラジオボタンを選択してフォーム送信をクリックすると、フォームデータはアクションメソッドでモデルに適切に逆シリアル化されますが、sexプロパティをチェックしているときにnullが表示されていることがわかりました価値。私は mvc を初めて使用し、フォームがアクションに送信されたときに性別プロパティが null になる理由を理解できません。
これが私の完全なコードです。どこで間違いを犯しているのか教えてください。ありがとう
コントローラーコード
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var student = new StudentModel
{
FirstName = "Rion",
LastName = "Gomes",
//I think the best way to populate this list is to call a service here.
Sex = new List<Sex>
{
new Sex{ID="1" , Type = "Male"},
new Sex{ID="2" , Type = "Female"}
}
};
return View(student);
}
[HttpPost]
public ActionResult Index(StudentModel model)
{
if (ModelState.IsValid)
{
//TODO: Save your model and redirect
}
//Call the same service to initialize your model again (cause we didn't post the list of sexs)
return View(model);
}
public ActionResult About()
{
return View();
}
}
型式コード
public class StudentModel
{
[Required(ErrorMessage = "First Name Required")] // textboxes will show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name Required")] // textboxes will show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
public string LastName { get; set; }
public List<Sex> Sex { get; set; }
}
public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}
これが私のビューコードです。
@model MvcRadioButton.Models.StudentModel
@{
ViewBag.Title = "Home Page";
}
@using(Html.BeginForm())
{
<div>
@Html.LabelFor(model => model.FirstName)
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div>
@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
foreach (var Sex in Model.Sex)
{
<div>
@Html.RadioButtonFor(model => model.Sex, Sex.ID, new { @id = ("sex" + Sex.ID) })
@*@Html.Label("Sex", sex.Type)*@
@Html.Label("sex" + Sex.ID, Sex.Type)
</div>
}
<input type="submit" value="Submit" />
}
また、性別プロパティに検証を設定する方法を教えてください。ラジオボタンを選択せずにフォームを送信しようとすると、メッセージが表示されます。ありがとう、私が間違っているところを教えてください。