モデルにいくつかのプロパティを追加するカスタム モデル バインダーがあります。
プロパティを追加するとすべて正常に動作しますが、既存のプロパティを更新するには、それらが無視されるようです。
私のコードは次のとおりです。
コントローラ
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(Deal model)
{
if (ModelState.IsValid)
{
model = _taskHelper.AddOrUpdateDeal(model);
}
return View(model);
}
モデルバインダー
public class DealModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, System.Type modelType)
{
if (modelType != typeof (Deal))
return base.CreateModel(controllerContext, bindingContext, modelType);
// Capture deal code
var dealCode = (string)bindingContext.ValueProvider.GetValue("DealCode").ConvertTo(typeof(string));
// Create a short URL for the deal
var shortUrl = "";
if (Uri.IsWellFormedUriString(dealCode, UriKind.Absolute))
{
// hardcoded for brevity
shortUrl = "http://amzn.to/1EDZm1r";
}
return new Deal()
{
DealCode = "XXXXX", // this never updates
DealNick = controllerContext.HttpContext.Request.Form["DealNick"] // this also never updates,
Price = Convert.ToDouble(controllerContext.HttpContext.Request.Form["Price"]) //this and the below start off empty so update fine,
Url = shortUrl,
DateCreated = DateTime.Now
};
}
}
簡潔にするために変更されたコードのコメントに注意してください。要約すると、フォームが送信されたときに最初に設定されていないものはすべて、問題なく更新できます。最初に設定されたものはすべて更新されません。
ありがとう