Frage

What is the best practice to protect model against unwanted parse/update after post in MVC3

Controller action called at HttpGet-> Product/Edit:

 public ActionResult Edit()
        {
          Product p = new Product();
          p.Id = 1;
          p.Name = "PC";
          Category cat = new Category();
          cat.Id = 1;
          cat.Name = "Non food";
          p.Category = cat;

          return View(p);
        }

This is the Edit View:

@model MvcApplication3.Models.Product
@using (Html.BeginForm("Edit", "Product", FormMethod.Post))
{
  @Html.HiddenFor(model => model.Id)
  @Html.EditorFor(model => model.Name)
  <input type="submit" value="Submit" name="go" />
}

After the browser gets the response, the user inserts the following html segment into the page:

<input type="text" value="5" name="Category.Id" id="Category_Id"/>

He posts the form, and the following controller action gets the "Product" parameter.

    //
    // POST: /Class1/Edit/5

    [HttpPost]
    public ActionResult Edit(Product p)
    {
      //Here: p.Company.Id is 5    !!!
      db.Save(p);
      return null;
    }

The problem is that the user should not be allowed to post/update the c.Company.Id. I would not like to check the whole parameter structure hunting for unwanted values. Im seeking for the best practice to solve the problem.

Any help is appreciated!

Bests,

Boolish

War es hilfreich?

Lösung

You could separate the received entity type (i.e. the ViewModel) from the entity type persisted to the database, as described in this recent blog post by Josh Bush. Well worth a read - topical too as it stems from the recent similar problem experienced by GitHub.

e.g.

public ActionResult Edit(ProductModel p)
{
    // Map ProductModel -> a Product instance
    // Then save
}

Andere Tipps

That's why you should use view models and not db entities in your views

http://blog.gauffin.org/2011/07/three-reasons-to-why-you-should-use-view-models/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top