Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Html.HiddenFor(x => x.Id) Does not work, but <input type="hidden" value = @Model.Id> works. Why?

I am really really confused rigthht now, because I thought that @Html.HiddenFor(x => x.Id) and <input id="Id" name="Id" type="hidden" [email protected]> is the same thing, except for some benefits of the first variant. But If I use the first variant and look into generated html value of input is always = 1, and if I use the second variant - everything is OK.

So here is my view model:

public class CheckListViewModel
{
    public int Id { get; set; }
    public DateTime CheckTime { get; set; }
    public List<QuestionViewModel> Questions { get; set; }
}

My view code:

@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" [email protected]>

    ...

MVC version is 5.2.0.0 Please, tell me, what have I done wrong, and why the @Html helper does not work properly?

UPDATE:

Contoller looks like this:

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);
}

Is my problem happening because I return one method result from another?

like image 741
Anarion Avatar asked Nov 20 '25 22:11

Anarion


1 Answers

Try change id name in action method for example questionId.

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

Upd: I have found SO question that exacly will help you.

SO question

like image 147
vborutenko Avatar answered Nov 23 '25 12:11

vborutenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!