I'm having a bit of an issue that I'd appreciate some help with.
I have a User object with properties ID and NAME that I need to display in a Readonly textbox. I'd like to populate the texbox's value with ID and Text with Name.
When submitted to Formcollection I need to retrieve entered data with:
collection.Get("User")
I know this is not the correct syntax but I'm trying to achieve the following:
@Html.TextBoxFor(model => model.User, new { @readonly="readonly",@Value = model.Id , @Text=model.Name })
What do I need to do to correct this ? In the textbox how can I display the user Name, when submitted return the user ID with collection.Get("User") ?
Thank you in advance.
p.s. Standard
@Html.TextBoxFor(model => model.User.Name)
doesn't work for me as it doesn't store the value and
@Html.TextBoxFor(model => model.User, new { @readonly="readonly",@Value = Model.User.Id})
fails for obvious reason when User.Id is empty (in my case it's possible ).
You need to store the Id in a hidden input field.
Keep in mind that as long as you use readonly, the value will be model-binded. But as soon as the field is disabled, it won't. So you will receive null values in your Controller.
In the Controller you can use Modelbinding instead of accessing the FormCollection.
Update:
Why do you wan't to have those values in the view in the first place?
If you need them for modelbinding you should be aware that people are still able to manipulate them even though they are readonly (Firebug, POST requests from other scripts).
If you require them for your model to be valid I would recommend using hidden input fields. And on the server side make sure that you only save values that the user is actually supposed to change.