Question

Imagine you have sent a model to a view... You are attempting to save this model once you edit it. If you don't write out all of the fields (that identity the object for instance), somehow they get reset to zero or empty (if it is string). What I did though, was write out a hidden field so that when I attempt to save this object, I am able to identify which object it is...

Is this good form? Or am I missing a step?

Était-ce utile?

La solution

If you've specified your model type to the view on the header of the file, and you are using the Html.BeginForm helper method, I'm pretty sure it will already take care of sending the id for you.

Edit: I tested it, and it's right. The Html.BeginForm method created the output

<form action="/Product/Edit/1" method="post">

That's why it sends the id.

Here's the Controller I used to test it:

using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class ProductController : Controller
    {
       public ActionResult Edit(int id)
        {            
            return View(new Product { Id = 1, Name = "Test"});
        }

        [HttpPost]
        public ActionResult Edit(Product product)
        {
            return Edit(product.Id);
        }

    }
}

and the View:

@model MvcApplication2.Models.Product

@using (Html.BeginForm()) {
    <fieldset>
        <legend>Product</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

Autres conseils

This is fine. as long as they wont edit the object identity, you can use the id as hidden input.

I would also recommend you to look at automapper if you are lazy writing out all the fields.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top