Pingpong
Pingpong

Reputation: 8009

Keeping Property value on HTTP POST, and is Read only on view, in ASP.NET MVC

I want to display a property as read only on a MVC view, and when the view is HTTP posted back, the property value remains, rather than null.

I tried the code, below but model binder return null,

@model Car

    @Html.DisplayFor(x => x.Name); //need to be read only, but returns the value on HTTP POST

    public class Car
    {
        public string Name { get; set; }
    }


 public ActionResult Index()
        {


            var car = new Car() {Name = "1"};
            return View(car);
        }

        [HttpPost]
        public ActionResult Index(Car car)  **//Name is NULL**
        {           
            return View(car);
        }

Thanks in advance!

Upvotes: 0

Views: 664

Answers (1)

itsmatt
itsmatt

Reputation: 31416

How about adding

@Html.HiddenFor(x => x.Name)

you can still put the @Html.DisplayFor(x => x.Name) on the page for display purposes.

Upvotes: 2

Related Questions