ca9163d9
ca9163d9

Reputation: 29159

Edit part of the fields?

I have the following model.

public class M
{
    public int Id { get; set; }
    public int A { get; set; }
    public int B { get; set; }
    public int C { get; set; }
    public int D { get; set; }
    ....
}

The Asp.Net Mvc 4 page need only edit one column. And I had to put @Html.HiddenFor() for all other columns - otherwise the database column for B, C, D.... will be reset to 0s. Is it a way to avoid it?

@model MyMvc.Models.M

@using (Html.BeginForm()))
{
    @Html.HiddenFor(m => m.Id)
    @Html.EditorFor(m => m.A)
    @Html.HiddenFor(m => m.B)
    @Html.HiddenFor(m => m.C)
    @Html.HiddenFor(m => m.D)
    ......
}

Upvotes: 0

Views: 65

Answers (2)

VahidNaderi
VahidNaderi

Reputation: 2488

You can just put a hidden field for Id and handle the others in your action method like this:

public ActionResult SaveM(M m)
{
    var mToEdit = db.find(m.Id);
    mToEdit.A = m.A;
    db.SaveChanges();
    //.......
}

Upvotes: 1

archil
archil

Reputation: 39501

HiddenFor just generates hidden field, but this never ensures that value will not be edited. Simple F12 click and anyone can edit value with developer tools. Instead, you should create ViewModel with that single field and check everything on server side

public class EditMViewModel
{
    public int A { get; set; }
}

And something like this in controller action

public ActionResult Edit(int id, EditMViewModel m)
{
    var someObject = LoadFromDb(id);
    if (ModelState.IsValid)
    {
        someObject.A = m.A;
        SaveToDb(someObject)
    }

    return RedirectToAction("Index");
}

Upvotes: 1

Related Questions