c# - 在 LabelFor() 控件中格式化文本

标签 c# asp.net-mvc-3

我正在尝试格式化价格标签,以便价格始终采用 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) })

Controller 代码如下:

[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>
}

最佳答案

我不确定 Controller 是什么样子的,但是拿这个测试版...

Controller

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new Product {Price = 9.99m};
            return View(model);
        }
    }

我创建了一个 Product 类作为示例..

 public class Product
    {
        public decimal Price { get; set; }
    }

然后您的 View 将需要引用模型

@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) })

您可以从 Controller 中看到构建模型并将其传递给 View 的位置。

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)

关于c# - 在 LabelFor() 控件中格式化文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26944530/

相关文章:

javascript - 如何使用 Javascript 打印带有图像的 Html 页面

asp.net - ModelClientValidationRule 冲突

c# - List<String> ByRef

c# - 如何在匿名类型中使用复杂的属性名称?

c# - 在 SSIS 中通过 C# 脚本向表添加派生列

c# - JSON.NET 忽略从 System.Exception 派生的类型中的属性。为什么?

asp.net-mvc-3 - .Net Mvc 3触发器(提交按钮除外)

c# - Ajax.ActionLink 不调用 Controller Action

c# - 使用 [JsonProperty] 将 Json 参数与类型为 List 的 C# 类属性匹配

c# - 在我的存储库中使用 LINQ 的方法会出现空错误