开发者

How to display and rebind data (not for editing) to ViewModel in ASP.NET MVC

开发者 https://www.devze.com 2023-02-15 08:52 出处:网络
I\'m using a custom ViewModel in the following general manner: public ActionResult Edit(int id) { // Attempt to fetch object from DB

I'm using a custom ViewModel in the following general manner:

    public ActionResult Edit(int id)
    {
        // Attempt to fetch object from DB
        var obj = Repository.GetObject(id);

        // Populate Dto
        var viewModel = new ObjectViewModel();
        var adapter = new ObjectAdapter(obj, viewModel, da);
        adapter.MapDto();

      开发者_StackOverflow社区  return View(viewModel);
    }

    public ActionResult Edit(int id, ObjectViewModel viewModel)
    {
        // Fetch object from DB
        var obj = Repository.GetObject(id);

        // Update object from DTO
        var adapter = new ObjectAdapter(obj, viewModel, da);
        adapter.MapObject();

        // Save back to DB
        Repository.SaveChanges();

        // Return to the Index
        return RedirectToAction("Index");

...

So then on my view, I want to display a bit of data but not for editing. At present I've tried:

<%: Model.Data %>

And I've tried a Html.Label(). They both display the data fine.

But the problem is this. On POST action, the "<%: Model.Data %>" or the label don't bind back to the ViewModel. So "MapObject()" will map null for "Model.Data" on the POST action.

I'm hoping (expecting) there's a simple solution here?

Any help greatly appreciated.

Cheers,

Tim.


Try adding a hidden field:

Html.HiddenFor(m => m.Data)

If you only write the value to the page with <%: Model.Data %> it won't get included when the form is submitted. The hidden field will submit with the form but, obviously, not be visible to the user.


What if you tried using the Html.LabelFor(x => x.Data)

UPDATED: Changed the Lambda expression from model to x.

0

精彩评论

暂无评论...
验证码 换一张
取 消