我遇到的问题似乎是在视图中更改了模型的值:
查看:
@model StudentTransportation.Models.PassengerVM
<div class="form-group">
@Html.LabelFor(model => model.PassengerID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PassengerID, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PassengerID, "", new { @class = "text-danger" })
</div>
<div>
型号:
public class PassengerVM
{
public int PassengerID { get; set; }
}
public PassengerVM()
{
PassengerID = 0;
}
控制器:
public ActionResult AddCompanion()
{
var companion = new PassengerVM();
return View("AddCompanion", companion);
}
HTML:
<div class="form-group">
<label class="control-label col-md-2" for="PassengerID">PassengerID</label>
<div class="col-md-10">
<input class="form-control text-box single-line" data-val="true" data-val-number="The field PassengerID must be a number." data-val-required="The PassengerID field is required." id="PassengerID" name="PassengerID" type="number" value="1">
<span class="field-validation-valid text-danger" data-valmsg-for="PassengerID" data-valmsg-replace="true"></span>
</div>
</div>
默认情况下,该值设置为0,但在视图中,它显示为1.任何建议?
当我将@ Model.PassengerID添加到HTML中时,它会显示正确的值。但是文本框仍然显示1
答案 0 :(得分:2)
你在某处有另一个名为@PassengerID的属性。当你这样做时:
@Html.TextBoxFor(model => model.PassengerID
“model”是HtmlHelper类型的对象,而不是PassengerVM! HtmlHelper类首先在URL上搜索属性,然后在HTTP post参数上搜索属性,最后在模型上搜索。但是,@ Model.PassengerId直接进入您的PassengerVM类型模型。
public ActionResult Edit(int id)
{
Pet pet = new Pet();
pet.Id = 7;
// If you navigate to /Pet/Edit/1 then @Html.TextBoxFor(m => m.Id)
// will show the Pet Id of "1" not "7"
return View(pet);
}
看看人们遇到类似问题的其他一些例子:
答案 1 :(得分:0)
我不能将此作为评论添加,但您尝试过...
@Html.TextBoxFor(model => model.PassengerID, new { htmlAttributes = new { @class = "form-control" } })
而不是EditorFor