ASP.NET MVC, can a controller change the entered values?

is ASP.NET MVC allowed to modify the values ​​presented?

[HttpPost]
public ActionResult Create(Person toCreate)
{
    toCreate.Lastname = toCreate.Lastname + "-A-";

    return View(toCreate);
}

I tried this code, but ASP.NET MVC continues to show user submitted values

[UPDATE]

[HttpPost]
public ActionResult Create(Person toCreate)
{
    return View(new Person { Lastname = "Lennon" });
}

or that:

[HttpPost]
public ActionResult Create(Person toCreate)
{
    return View();
}

still showing the values ​​entered by the user, which made me wonder why the generated code should emit: return View (toCreate) in HttpPost? why not just return View ()? at least this does not violate the expectation that values ​​can be redefined from the controller

[UPDATE: 2010-06-29]

Found the answer here: ASP.NET MVC: changing model properties during postback and here: Setting ModelState values ​​in a custom model binder

Work code:

[HttpPost]
public ActionResult Create(Person toCreate)
{
    ModelState.Remove("Lastname");
    toCreate.Lastname = toCreate.Lastname + "-A-";
    return View(toCreate);
}
+3
3

-, ModelState . IsValid , .

, , IsValid, . , ModelState , , IsValid true.

:

bindingContext.ModelState.Remove("Slug");
    bindingContext.ModelState.Add("Slug", new ModelState());
    bindingContext.ModelState.SetModelValue("Slug", new ValueProviderResult(obj.Slug, obj.Slug, null));
+4

, .

, .

Model.Lastname

Create.aspx?

0

Html- , :

<%= Html.TextBox("toCreate.LastName", Model.Person.LastName) %>

When a page is displayed with POST, by default the helper displays the value sent in the POST data. That is, it only uses Model.Person.LastName for the first time (GET). This is usually the preferred approach, but if you want to avoid this, just write html yourself:

<input type="text" name="toCreate.LastName" value="<%= Html.Encode(Model.Person.LastName)" />
0
source

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


All Articles