In MVC Edit Action {HTTP POST} Using UpdateModel vs Request.Form Collection

I am working on a sample MVC Nerdinner tutorial and use it in the AdventureWorks database. I created the "Edit" action in the CategoryController to edit the product category in AdventureWorks. The only field to be updated in this table is Name (other fields - ID, RowGUID and UpdateDate are automatically generated). Thus, my right View form has only 1 field for the name (product category). My Save action for editing is shown below: -

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection collection){
        ProductCategory p = awRepository.GetProductCategory(id);
        try
        {
            //UpdateModel(p);
            p.Name = Request.Form["Name"];
            awRepository.Save();
            return RedirectToAction("Details", new { id = p.ProductCategoryID });
        }
        catch
        {
            foreach (var err in p.GetRuleViolations())
            {
                ModelState.AddModelError(err.PropertyName, err.ErrorMessage);
            }
            return View(p);
        }
    }

, , , , , ( , ). ( GetRuleViolations, "" ), NullReferenceException ( , ) (Category/Edit.aspx), Edit View ( )

     <%= Html.TextBox("Name") %>

ProductCategory UpdateModel (p) Request.Form, ; , , .

: UpdateModel , Request.Form? Nerdinner, , , . , , .

+3
1

:

http://forums.asp.net/p/1396019/3006051.aspx

, , ModelState.AddModelError() MVC Framework "" . , MVC .

values: Values , DefaultBinding ( UpdateModel() : ActionResult (FormCollection Form, YourObjectType yourObject).

, UpdateModel, ?

if (Form["Name"].Trim().Length == 0)
{    
    ModelState.AddModelError("Name", "Name is required");    

    //You missed off SetModelValue?
    ModelState.SetModelValue("Name", Form.ToValueProvider()["Name"]); 
}
+1

Source: https://habr.com/ru/post/1751733/


All Articles