@Html.HiddenFor(x => x.Id)不起作用,但<input type="hidden" value = @Model.Id>可以。为什么?

3
我现在非常困惑,因为我以为 @Html.HiddenFor(x => x.Id)<input id="Id" name="Id" type="hidden" value=@Model.Id> 是相同的,除了第一个变量具有一些优势。但是如果我使用第一个变量并查看生成的 HTML 值,则输入值始终为 1,如果我使用第二个变量,则一切正常。
所以这是我的视图模型:
public class CheckListViewModel
{
    public int Id { get; set; }
    public DateTime CheckTime { get; set; }
    public List<QuestionViewModel> Questions { get; set; }
}

我的视图代码:

@using System.Diagnostics
@using WebCheckList.Models
@model  CheckListViewModel
@using (Html.BeginForm("Submit", "CheckList", new {ReturnUrl = ViewBag.ReturnUrl}, FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
{
    //this one does not work. It generates the same html code as 
    // a line below it, only difference is that its value is always = 1
    @Html.HiddenFor(x => x.Id); 
    //When I change it to this - everything works.
    <input id="Id" name="Id" type="hidden" value=@Model.Id>

    ...

MVC版本为5.2.0.0。请告诉我,我做错了什么,为什么@Html助手无法正常工作?

更新:

控制器如下:

public ActionResult Questions(int  id)
{
    return Create(new CheckList(), id);
}

public ActionResult Create(CheckList checkList, int checkListsTypeID = 2)
{
    _db.CheckLists.Add(checkList);
    _db.SaveChanges();

    var checkListViewModel = new CheckListViewModel {Questions = questions, Id = checkList.ID, CheckTime = checkList.CheckTime};
    return View("Details", checkListViewModel);
}

我的问题是因为我从另一个方法返回了一个结果吗?

我认为你应该提供控制器代码。你在控制器代码中改变了id吗? - vborutenko
1个回答

3
尝试在操作方法中更改ID名称,例如questionId。
public ActionResult Questions(int  questionId)
{
    return Create(new CheckList(), id);
}
更新: 我找到了一个完全可以帮助你的Stack Overflow问题。 这个问题

1
那是一些意外的行为。 - Anarion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接