Этот вопрос немного отличается от большинства. Мой код работает, но я не понимаю, почему он работает.
Я пытаюсь понять, почему изменения, внесенные в форму, сохраняются после отправки на сервер.
Модель:
public class TestUpdateModel
{
public int Id { get; set; }
public List<CarrierPrice> Prices { get; set; }
public TestUpdateModel() { } // parameterless constructor for the modelbinder
public TestUpdateModel(int id)
{
Id = id;
Prices = new List<CarrierPrice>();
using (ProjectDb db = new ProjectDb())
{
var carriers = (from c in db.Carriers
select c);
foreach (var item in carriers)
{
var thesePrices = item.Prices.Where(x => x.Parent.ParentId == Id);
if (thesePrices.Count() <= 0)
{
Prices.Add(new CarrierPrice
{
Carrier = item
});
}
else
Prices.Add(thesePrices.OrderByDescending(x => x.DateCreated).First());
}
}
}
}
Контроллер:
public ViewResult Test(int id = 1)
{
TestUpdateModel model = new TestUpdateModel(id);
return View(model);
}
[HttpPost]
public ViewResult Test(TestUpdateModel model)
{
model = new TestUpdateModel(model.Id);
return View(model); // when model is sent back to view, it keeps the posted changes... why?
}
View
@model Namespace.TestUpdateModel
@{ ViewBag.Title = "Test"; }
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Id)
@Html.EditorFor(x => x.Prices)
<input type="submit" value="Save" />
}
EditorTemplate
@model Namespace.CarrierPrice
<tr>
<th>
@Html.HiddenFor(model => model.CarrierPriceId)
@Html.HiddenFor(model => model.DateCreated)
@Model.Carrier.Name
</th>
<td>
$@Html.TextBoxFor(model => model.Fee)
</td>
</tr>
Источник моей путаницы
1) Загрузить страницу в браузере
2) Измените значение модели. Текстовое поле
3) Отправить
В этот момент я ожидаю, что model = new TestUpdateModel(model.Id);
создаст новый объект TestUpdateModel и уничтожит мои изменения, чтобы исходные значения снова появлялись при возврате представления. Но на самом деле мои изменения в форме сохраняются до обратной передачи.
Почему это происходит?
Спасибо за любую помощь.