View not updating after post

2020-01-28 04:11发布

I have a controller method CreateOrUpdate, this method is supposed to save the car to the database and then return as normal.

public ActionResult CreateOrUpdate(int ID = 0)
{
    Car car = new Car(ID);
} 

[HttpPost]
public ActionResult CreateOrUpdate(Car car)
{
       car.Save();
       return View(car);
}

In the theCar.Save() method, i set the id for the car, with whatever the id will be in the database after the car is saved (When doing an insert I use SCOPE_IDENTITY(), the save method works well, and if i debug and watch the values for car after the Save() is called, the id is correct. But when the View is rendered the ID is 0 in the view.

Could anyone please help me,and tell me why this would happen. Am I not suppose to change the Model for the view in the HTTP POST method ? Should i Rather redirect to the original CreateOrUpdate() method if the save was successful.

3条回答
该账号已被封号
3楼-- · 2020-01-28 04:35

I didn't want to clear the ModelState because I needed to display errors, so I went with

ValueProviderResult vpr = new ValueProviderResult("", null, System.Globalization.CultureInfo.CurrentCulture);

ModelState["id"].Value = vpr;
查看更多
该账号已被封号
4楼-- · 2020-01-28 04:59

it should be the ModelState problem. if you use Htmlhelper to Display id value. Default HtmlHelper display ModelState value not Model. Try display model value in view

<td>
    @Model.id
</td>

or Clean ModelState Value in controller

ModelState.Clear();

or reset id value after SaveChange.

theCar.Save();
ModelState["id"].Value = theCar.id
return View(theCar);

Reset the value of textarea after form submission

查看更多
登录 后发表回答