Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat Is The Best Practice To Deal With MVC Post Models?
    primarykey
    data
    text
    <p>I'm pretty new to MVC and still confused what the best and proper way for 2 cases for with same result. Let's say some user should add new sub category for specific root category.</p> <p><strong>Case 1:</strong> SubCategory is a mapped class by EF where all properties not nullable.</p> <p>Controler:</p> <pre><code> [Authorize] public ActionResult Create() { SubCategory subCategory = new SubCategory(); subCategory.RootCategoryID = 1; return View(subCategory); } [Authorize] [HttpPost] public ActionResult Create(SubCategory thisSubCategory) { if (ModelState.IsValid) { //And some BL logic called here to handle new object... } } </code></pre> <p>View:</p> <pre><code> @Html.HiddenFor(model =&gt; model.ID) @Html.HiddenFor(model =&gt; model.RootCategoryID) &lt;h3&gt;Sub Category Name: &lt;/h3&gt; @Html.EditorFor(model =&gt; model.CategoryName) @Html.ValidationMessageFor(model =&gt; model.CtaegoryName) &lt;input id="btnAdd" type="submit" value="Add" /&gt; </code></pre> <p><strong>Case 2:</strong> Add helper class as controller's model and populate EF object after post</p> <p>Controler:</p> <pre><code> class SubCategoryHelper { public string Name { get; set; } } [Authorize] public ActionResult Create() { SubCategoryHelper subCategory = new SubCategoryHelper(); return View(subCategory); } [Authorize] [HttpPost] public ActionResult Create(SubCategoryHelper thisSubCategory) { if (ModelState.IsValid) { SubCategory newSubCategory = new SubCategory(); newSubCategory.RootCategoryID = 1; newSubCategory.CtaegoryName = thisSubCategory.Name; //And some BL logic called here to handle new object... } } </code></pre> <p>View: <h3>Sub Category Name: </h3></p> <pre><code> @Html.EditorFor(model =&gt; model.Name) @Html.ValidationMessageFor(model =&gt; model.Name) &lt;input id="btnAdd" type="submit" value="Add" /&gt; </code></pre> <p>Both ways makes the same, but the first way looks less secure because of the hiddens that could be changed on the client side. The second way much longer, imagine the same way for rich objects such as Client or Product... What should I choose? Or there is some other way?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload