我有一个自定义模型绑定器,它为我的模型添加了一些属性。
向它添加属性时一切正常,但是我要更新任何现有属性,似乎那些被忽略了。
我的代码如下:
控制器
[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
};
}
}
请注意代码上的注释,为简洁起见已对其进行了修改。总之,提交表单时最初未设置的任何内容都可以毫无问题地更新。最初设置的任何内容都不会更新。
谢谢