I have a scenario where I create “Machine” entities that are associated with the logged in user (windows authentication) that created them. The user is only ever created in the database once they have created at least one Machine entity.
I’m using model binding on the create Machine form. The Machine model has an associated User entity, a custom one that looks like this:
public class User
{
public int UserId { get; set; }
[DisplayName("User")]
public string Username { get; set; }
public string Email { get; set; }
public int SectorId { get; set; }
public Sector Sector { get; set; }
public List<Machine> Machines { get; set; }
}
So far, in the create machine view I have created a hidden input for the user name using the following:
@Html.HiddenFor(model => model.User.Username, new { User.Identity.Name })
But I’m finding that this is not populated in the model when it is returned to the HttpPost create handler.
I was wondering how I might be able to pass the username down with the model?
First off, the problem you’re having with your
HiddenFor()method call is that the second parameter is supposed to be anobjectfor htmlAttributes. So your method call isn’t correct. (MSDN Reference for theHiddenFor()method):Why are you trying to populate this within the View? Take this logic to the controller: