Question

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 ).

Was it helpful?

Solution

You need to store the Id in a hidden input field.

@Html.HiddenFor(x => x.User.Id)
@Html.TextBoxFor(x => x.User.Name, new { @readonly = "readonly" })

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.

public ActionResult Whatever(User user)
{
    // user.Id
    // user.Name 
    // should be filled.
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top