停止EditorFor<比;从添加0到int属性
本文关键字:int 属性 添加 EditorFor 停止 | 更新日期: 2023-09-27 17:50:56
我有一个视图模型,有几个属性是int
,当我在视图中使用@Html.EditorFor
时,生成一个文本框,但它用数字0填充它。我不希望文本框预填充任何,我怎么能停止这个而不使属性为空?
ViewModel:
public class TransactionVM
{
[DisplayName("Ticket #"), DataType(DataType.Text)]
public int TicketNumber { get; set; }
[DisplayName("Customer")]
public IEnumerable<SelectListItem> Customers { get; set; }
public int CustomerId { get; set; }
[DisplayName("Carrier")]
public IEnumerable<SelectListItem> Carriers { get; set; }
public int CarrierId { get; set; }
[DisplayName("Driver")]
public IEnumerable<SelectListItem> Drivers { get; set; }
public int DriverID { get; set; }
[DisplayName("Product")]
public IEnumerable<SelectListItem> Products { get; set; }
public int ProductId { get; set; }
[DisplayName("Gross Gallons'n(Max: 6,000)")]
public decimal GrossGallons { get; set; }
[DisplayName("Net Gallons")]
public decimal NetGallons { get; set; }
[DisplayName("Sale Start Number")]
public string SaleStartNumber { get; set; }
[DisplayName("Transaction Date and Time")]
public DateTime TransactionDate { get; set; }
}
控制器:
TransactionVM model = new TransactionVM();
return View(model);
using (var db = new DynamicDbContext())
{
model.Customers = new SelectList(db.GetList<Customer>(c => c.Id > 0).ToList(), "Id", "Name");
return View(model);
}
视图:
<tr>
<td>
@Html.LabelFor(m => m.TicketNumber)
</td>
<td>
@Html.EditorFor(m => m.TicketNumber)
</td>
</tr>
这不是关于禁用模型绑定。我想在视图中放置数据以填充下拉菜单,并且还需要将所有数据绑定到post上以便在控制器中操作。
我不确定,没有尝试,但你可以尝试设置value
属性像这样:
@Html.EditorFor(m => m.TicketNumber, new { @value = "" })
编辑:另一种方法是使用jQuery
:
<script>
$(function() {
$("#TicketNumber").val("");
});
</script>
将[DefaultValue(null)]
dataannotation添加到模型属性中。或者至少在控制器动作中设置默认值(使用[HttpGet]
)来准备页面!或者在客户端通过jQuery删除value属性
将模型属性设置为Nullable的另一种方法是直接编辑ModelState。
public ActionResult Create()
{
var model = new TransactionVM();
ModelState.SetModelValue("TicketNumber", new ValueProviderResult("", "", System.Globalization.CultureInfo.CurrentCulture));
return model;
}
在POST操作中也必须小心这样做,然后只有在值为0
的情况下。