我有这个带有必需属性的模型。是的,它们是创建项目所必需的,但是当我想更新它们的单个列时,我收到有关必填字段的错误。所以我的控制器似乎想要更新所有这些。
在这种情况下,有一个待售商品,可以为它提供报价。
我的部分模型:
public class Ad
{
public int AdID { get; set; }
[Required()]
[Display(Name = "Otsikko")]
public string Title { get; set; }
[Required()]
[DataType(DataType.MultilineText)]
[AllowHtml]
[Display(Name = "Kuvaus")]
public string Text { get; set; }
[Required()]
[DataType(DataType.Currency)]
[Display(Name = "Hinta")]
public float Price { get; set; }
[DataType(DataType.Currency)]
[Display(Name = "Tarjottu")]
public float Offer { get; set; }
我的控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Offer([Bind(Include = "Offer")] Ad ad)
{
if (ModelState.IsValid)
{
db.Entry(ad).State = EntityState.Modified;
db.SaveChanges();
return RedirectToRoute("ilmoitus", new { id = ad.AdID });
}
else
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}
}
部分观点:
@using (Html.BeginForm("Offer", "Ads"))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.AdID)
@Html.EditorFor(model => model.Offer, new { htmlAttributes = new { @class = "form-control offer-input", @placeholder = "Tarjoa..." } })
<button class="btn-default btn offer-btn">Tarjoa {{offer}} €</button>
}
答案 0 :(得分:1)
我让它像这样工作,包括隐藏的所有其他属性并将它们绑定在控制器中:
查看:
@using (Html.BeginForm("Offer", "Ads"))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.AdID)
@Html.HiddenFor(model => model.Title)
@Html.HiddenFor(model => model.Text)
@Html.HiddenFor(model => model.Price)
@Html.HiddenFor(model => model.Location)
@Html.HiddenFor(model => model.PaymentOptions)
@Html.HiddenFor(model => model.DeliveryOptions)
@Html.HiddenFor(model => model.SellerEmail)
@Html.EditorFor(model => model.Offer, new { htmlAttributes = new { @class = "form-control offer-input", @placeholder = "Tarjoa..." } })
<button class="btn-default btn offer-btn">Tarjoa {{offer}} €</button>
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Offer([Bind(Include = "AdID,Title,Text,Price,Offer,Location,PaymentOptions,DeliveryOptions,SellerEmail")] Ad ad)
{
if (ModelState.IsValid)
{
db.Entry(ad).State = EntityState.Modified;
db.SaveChanges();
return RedirectToRoute("ilmoitus", new { id = ad.AdID });
}
else
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}
}
这是安全问题吗?
答案 1 :(得分:0)
我对上述查询有两个解决方案。
您可以使用两种不同的模型进行更新和插入example
从 ModelState 中移除属性,然后尝试TryUpdateModel
public ActionResult UpdateAd(Ad ad)
{
ModelState.Remove("Title");
ModelState.Remove("Text");
ModelState.Remove("Price");
var p = GetAd();
if (TryUpdateModel(p))
{
//Save Changes;
}
}