I have two ViewModel
s with the one referencing the other:
public class GiveViewModel
{
[Required]
public int GivenLifelines { get; set; }
public string ToUser { get; set; }
public string FromUser { get; set; }
}
public class UserDetailsViewModel
{
public GameDetail gameDetail { get; set; }
public UserDetail userDetail { get; set; }
public IEnumerable<GameItem> gameItems { get; set; }
public IEnumerable<UserDetail> allUsers { get; set; }
//REF
public GiveViewModel givenLifeLines { get; set; }
}
The main viewmodel
is used in the controller to get all the info on the foreign keys for the page. I have IEnumerable
s to list all users and game items, and references to the main models to get the current users details. This enables users to give points to other users while on their details page (the DetailsController
).
Technically I do not use the givenLifeLines
on the first load for the view. It is only used during the POST.
I can get the values back from the POST and use it on the [HttpPost]
controller
but it seems a bit awkward.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Give(UserDetailsViewModel model)
{
int givenLifeLines = model.givenLifeLines.GivenLifelines; //got value
string givenTo = model.givenLifeLines.ToUser; // got value
....
}
You see, the current logged in user selects another user based on their image by clicking the selected image:
<img src="~/@item.AppImage.ImagePath" class="img-responsive img-thumbnail user-image" data-username="@item.FirstName" style="width:100px;height:100px;" />
which gets added to a model textbox:
@Html.TextBoxFor(model => model.givenLifeLines.ToUser, new { @class = "give-to form-control" })
That process is controlled by jQuery:
$(".user-image").click(function () {
$(".give-to").val($($(this)).attr('data-username'));
})
This all works fine. I am getting the values I need in the model for the POST, but I get the feeling that this is not a good idea. Ideally I would want the textbox to be disabled, however, if I do that, the value is then not passed to POST controller model. A dirty work around would be to just display:none
on the textbox and still have it enabled but that would feel wrong. I don't feel like I should be required to depend on jQuery like this.
Is there a better way to approach this that is more inline with the practices of model binding? Should I be separating my ViewModel
s like I have?