【问题标题】:@Html.HiddenFor(x => x.Id) Does not work, but <input type="hidden" value = @Model.Id> works. Why?@Html.HiddenFor(x => x.Id) 不起作用,但 <input type="hidden" value = @Model.Id> 起作用。为什么?
【发布时间】:2014-09-04 18:06:02
【问题描述】:

我现在真的很困惑,因为我认为@Html.HiddenFor(x =&gt; x.Id)&lt;input id="Id" name="Id" type="hidden" value=@Model.Id&gt; 是一样的,除了第一个变体的一些好处。但是,如果我使用第一个变体并查看生成的 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 吗?

标签: c# asp.net-mvc asp.net-mvc-5


【解决方案1】:

尝试在 action 方法中更改 id 名称,例如 questionId。

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

更新: 我发现这样的问题对你有帮助。

SO question

【讨论】:

  • 那里有一些意想不到的行为。
猜你喜欢
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多