首先,我懷疑可能與我的下面的問題或原因有關。 我不知道是什麼在視圖下方兩個句子之間的區別:當複選框被選中時,模型未被更新
@model MyProject.SampleModel.CustomModels
@using MyProject.SampleModel;
我的模型:
Namespace MyProject.SampleModel
{
public class ViewModelExample {
public FirstModel BoolValues { get; set; }
public SecondModel NamesValues { get; set; }
}
}
Namespace MyProject.SampleModel
{
public class FirstModel
{
public bool MyBoolean1 { get; set; }
public bool MyBoolean2 { get; set; }
}
public class SecondModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
其次,我有檢查的複選框之一,當一個問題查看:它看起來像它的模型沒有被正確更新,或者在某些時候被更新和值覆蓋,因爲我有一個javascript函數,當我按下視圖的按鈕時它會檢查這個複選框的狀態,並且它根據是否執行某些操作它被檢查與否。當我從javascript函數中獲得這個值時,即使我已經檢查過,它總是假的。我不知道發生了什麼,也許我沒有以正確的方式初始化我的模型等。
下面我的視圖代碼,也是一塊控制器。
查看:
@model MyProject.SampleModel.ViewModelExample
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, htmlAttributes: new { id = "Myform" }))
{
(...)
@Html.CheckBoxFor(m => m.BoolValues.MyBoolean1) <-- i check this in the view
(...)
<input id="submitButton" type="button" value="Add" /> <-- button that I click on
(...)
}
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
(...)
$(function(){
$('#submitButton').on('click', InitiateSequence);
});
function InitiateSequence()
{
// Do some stuff
ScriptSample();
}
(...)
function ScriptSample() {
if(@(Model.BoolValues.MyBoolean1 ? "true" : "false") <-- This is always FALSE and should be TRUE because i have checked the checkbox in the view before click on the button
{
// It's true, do some stuff
}
else
{
// It's false, do some stuff
}
}
</script>
控制器:
public ActionResult MyAction(ViewModelExample model)
{
// Below initialization I am not sure if it is correct
if (model.FirstModel == null)
{
model.FirstModel = new TestsModel(); // I do not instantiate SecondModel as in the view for this controller i do not use it
}
return View(model);
}