首先,我怀疑可能与我的以下问题或原因有关。我不知道视图中以下两句话有什么区别:
@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);
}