在 LabelFor() 控件中设置文本格式
本文关键字:置文本 格式 控件 LabelFor | 更新日期: 2023-09-27 18:30:37
我正在尝试格式化价格标签,以便价格始终采用 0.00 格式,我在下面看到了一个类似的问题,它使用了与我类似的代码。我收到一个object reference not set to an instance of an object
错误,我知道这是因为我正在打电话Model.Price
但我对 MVC 很陌生,我不明白在加载页面之前如何设置Model.Price
。
@Html.LabelFor(model => model.Price, "0.00", new { id = "priceLabel", Value = String.Format("{0:C}", Model.Price) })
下面是控制器代码:
[HttpGet]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
// set the paper style list
List<SelectListItem> styles = new List<SelectListItem>();
ViewBag.paperStyle = new SelectList(styles, "Value", "Text");
// set the subject list
List<SelectListItem> subjects = new List<SelectListItem>();
ViewBag.subject = new SelectList(subjects, "Value", "Text");
// set the number of pages list
List<SelectListItem> numberOfPages = new List<SelectListItem>();
ViewBag.Urgency = new SelectList(urgency, "Value", "Text");
// set the document type list
List<SelectListItem> documentTypes = new List<SelectListItem>();
ViewBag.documentType = new SelectList(documentTypes, "Value", "Text");
// set the academic level list
List<SelectListItem> academicLevel = new List<SelectListItem>();
ViewBag.academicLevel = new SelectList(academicLevel, "Value", "Text");
// set the number of sources list
List<SelectListItem> numberOfSources = new List<SelectListItem>();
ViewBag.numberOfSources = new SelectList(numberOfSources, "Value", "Text");
// set the currency list
List<SelectListItem> currencies = new List<SelectListItem>();
currencies.Add(new SelectListItem() { Text = "$", Value = "USD", Selected = true });
currencies.Add(new SelectListItem() { Text = "£", Value = "GBP", Selected = false });
currencies.Add(new SelectListItem() { Text = "€", Value = "EUR", Selected = false });
ViewBag.currency = new SelectList(currencies, "Value", "Text");
return View();
}
[HttpPost]
public ActionResult Contact(WritingAppModel c)
{
if (ModelState.IsValid)
{
// send the email and process the payment
// if payment is ready then send email
if (isPaymentReady())
{
// send email
}
}
return View();
}
public class modelData
{
public string documentType { get; set; }
public string numberOfPages { get; set; }
public string urgency { get; set; }
}
public JsonResult getNewPrice(modelData dropdownValues)
{
// check for urgency first since that is the base price
if (dropdownValues.urgency != null)
{
currentPrice = Convert.ToDecimal(dropdownValues.urgency);
if (dropdownValues.documentType != null)
{
currentPrice = currentPrice + Convert.ToDecimal(dropdownValues.documentType);
if (dropdownValues.numberOfPages != null)
{
currentPrice = currentPrice * Convert.ToInt16(dropdownValues.numberOfPages);
}
}
}
// do something with value and return a decimal
return Json(new { currentPrice = currentPrice }, JsonRequestBehavior.AllowGet);
}
下面是视图代码:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<div class="row">
@Html.LabelFor(model => model.Name, "Name:")
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="row">
@Html.LabelFor(model => model.Email, "Email:")
@Html.TextAreaFor(model => model.Email, new { id = "email" })
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="row">
@Html.LabelFor(model => model.Topic, "Topic:")
@Html.EditorFor(model => model.Topic)
@Html.ValidationMessageFor(model => model.Topic)
</div>
<div class="row">
@Html.LabelFor(model => model.Subject, "Subject:")
@Html.DropDownListFor(model => model.Subject, (SelectList)ViewBag.subject, "--Select--", new { id = "subjectList" })
</div>
<div class="row">
@Html.LabelFor(model => model.Style, "Style:")
@Html.DropDownListFor(model => model.Style, (SelectList)ViewBag.paperStyle, "--Select--", new { id = "paperStyleList" })
</div>
<div class="row">
@Html.LabelFor(model => model.DocumentType, "Document Type:")
@Html.DropDownListFor(model => model.DocumentType, (SelectList)ViewBag.documentType, "--Select--", new { id = "documentTypeList" })
</div>
<div class="row">
@Html.LabelFor(model => model.AcademicLevel, "Academic Level:")
@Html.DropDownListFor(model => model.AcademicLevel, (SelectList)ViewBag.academicLevel, "--Select--", new { id = "academicLevelList" })
</div>
<div class="row">
@Html.LabelFor(model => model.NumberOfPages, "Number of Pages/Words:")
@Html.DropDownListFor(model => model.NumberOfPages, (SelectList)ViewBag.numberOfPages, "--Select--", new { id = "numberOfPagesList" })
</div>
<div class="row">
@Html.LabelFor(model => model.NumberOfSources, "Number of Sources:")
@Html.DropDownListFor(model => model.NumberOfSources, (SelectList)ViewBag.numberOfSources, "--Select--", new { id = "numberOfSourcesList" })
</div>
<div class="row">
@Html.LabelFor(model => model.Urgency, "Urgency:")
@Html.DropDownListFor(model => model.Urgency, (SelectList)ViewBag.urgency, "--Select--", new { id = "urgencyList" })
</div>
<div class="row">
@Html.LabelFor(model => model.Spacing, "Spacing:")
@Html.RadioButtonFor(model => model.Spacing, "Single") Single
@Html.RadioButtonFor(model => model.Spacing, "Double") Double
</div>
<div class="row">
@Html.LabelFor(model => model.Requirements, "Requirements:")
@Html.TextAreaFor(model => model.Requirements)
</div>
<div class="row">
@Html.DropDownListFor(model => model.Currency, (SelectList)ViewBag.currency, null, new { id = "currencyList" })
<h2>
@Html.LabelFor(model => model.Price, "{0:C}", new { id = "priceLabel" })
</h2>
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</div>
}
我不确定控制器是什么样子的,但请接受这个测试版本...
控制器
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new Product {Price = 9.99m};
return View(model);
}
}
我创建了一个产品类作为示例。
public class Product
{
public decimal Price { get; set; }
}
然后,您的view
将需要引用model
。
@model WebApplication2.Controllers.Product
@Html.LabelFor(model => model.Price, new { id = "priceLabel" })
@Html.TextBoxFor(model => model.Price, new { id = "priceLabel",
Value = String.Format("{0:C}", Model.Price) })
您可以从控制器中看到模型的生成位置并传递到视图的位置。
var model = new Product {Price = 9.99m};
return View(model);
LabelFor
将为实际属性生成标签,而不是其值。
编辑:基于评论。
如果您只想显示该属性...
@String.Format("{0:C}", Model.Price)
或者,正如史蒂夫所建议的那样...
型号:
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Price { get; set; }
视图
@Html.DisplayFor(model => model.Price)