Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input hidden shows incorrect Id (Guid.Empty)

I want to have an input (hidden) field that stores Id of some entity...

But this code:

@Html.HiddenFor(model => model.Id)

Results in this HTML markup:

<input id="Id" name="Id" type="hidden" value="00000000-0000-0000-0000-000000000000" />

This is weird since I'm sure that Model.Id != Guid.Empty. I can cofirm it by injecting @Model.Id into HTML. This works fine:

<input type="hidden" id="Id" name="Id" value="@Model.Id" />

Why View Engine decides to put these zeros instead of correct Id?

Edit: I didn't add original code because it is quite complicated but here is super simple sample that shows almost the same behavior (it uses empty string not Guid.Empty in input value):

View:

@using MvcApplication4.Models
@model Foo

@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.Id)
    @Model.Id

    <input type="submit" value="ok" />
}

Controller:

namespace MvcApplication4.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            Foo foo = new Foo();
            return View(foo);
        }  

        [HttpPost]
        public ActionResult Index(Foo foo)
        {
            foo.Id = Guid.NewGuid();
            return View(foo);
        } 
    }
}

Model:

using System;

namespace MvcApplication4.Models 
{
    public class Foo
    {
         public Guid? Id { get; set; }
    }
}

Problem is of course visible after post action.

like image 340
user1068352 Avatar asked Dec 26 '12 16:12

user1068352


1 Answers

and that explains everything. You are experiencing the same problem as another person in this question. Please see accepted answer and the comments to it as it's relevant to your issue.

like image 81
Dmitry Efimenko Avatar answered Sep 28 '22 08:09

Dmitry Efimenko