HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Using readonly input fields to persist data between views

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fieldsinputviewsbetweenusingpersistreadonlydata

Problem

I'm building a multi-screen Ajax form in an ASP.NET MVC solution. The first screen displays some user details. If the user clicks 'edit', they are taken to the next screen where they can edit the fields. The call to retrieve the user info is quite slow so I don't want to repeat it for every Ajax request, so I'm thinking of displaying the information on the first screen using @Html.TextBoxFor(m=>m.FieldName, new {@readonly="readonly"}) (styled so it doesn't look like an ordinary readonly input). Then simply posting this information back and re-using it when I show the edit screen.

My initial screen to show existing info (Index.cshtml) is something like this (note that there are more fields, I just showed one to demonstrate the idea):

@using(Ajax.BeginForm("StartEdit", "UserDetails", new AjaxOptions{...})
{
    
        @Html.LabelFor(m=>m.FirstName)
        @Html.TextBoxFor(m=>m.FirstName, new { @readonly = "readonly" })
    
    
}


and the edit screen (Edit.cshtml) is something like this:

@using(Ajax.BeginForm("SubmitChanges", "UserDetails", new AjaxOptions{...})
{
    
        @Html.LabelFor(m=>m.FirstName)
        @Html.TextBoxFor(m=>m.FirstName)
    
}


The controller is as follows:

public class UserDetailsController
{
    public PartialViewResult Index()
    {
        var viewModel = new MyViewModel(); //populated from web service, slow operation
        return PartialView("Index", viewModel);
    }

    public PartialViewResult(MyViewModel viewModel)
    {
        return PartialView("Edit", viewModel); //returning posted viewModel back to next view
    }

}


Is there anything wrong with doing this, or should I just use hidden fields to persist the information and render that same information to the user using @Html.DisplayFor(m=>m.FieldName) etc?

Solution

On a functional level there is no problem with using readonly inputs to persist and display data in a preview screen. When I tried this approach however I noticed that different browsers treat readonly inputs in different ways which cannot be addressed with CSS rules. For example in Chrome the inputs can be styled to look and behave like any other element, however in IE the caret will sit there blinking on readonly input fields which was not acceptable in my particular case.

Context

StackExchange Code Review Q#64579, answer score: 2

Revisions (0)

No revisions yet.