ASP.NET MVC#显示格式问题
我要直截了当地说 我试图显示ASP.NET MVC#显示格式问题,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我要直截了当地说 我试图显示月收入,使其只有2位小数 我尝试过使用DisplayFormat,但是当我将它添加到文本框中时,它不起作用 型号 public class AgentModel { [Display(Name = "Monthly Income")] [DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)] public decimal MonthlyIncome
月收入
,使其只有2位小数
我尝试过使用DisplayFormat
,但是当我将它添加到文本框中时,它不起作用
型号
public class AgentModel
{
[Display(Name = "Monthly Income")]
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public decimal MonthlyIncome { get; set; }
}
查看
//this input display the two decimal
@Html.EditorFor(m => m.MonthlyIncome, new { htmlAttributes = new { @class = "form-control" } })
//this one display 5 decimal
@Html.TextBoxFor(m => m.MonthlyIncome, new { @class = "form-control"})
@model HelloWorldMvcApp.SampleViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(m => m.Question)
@Html.TextBoxFor(model => model.Question, new {@class="form-control"})
@Html.ValidationMessageFor(model => model.Question)
</div>
@Html.DisplayFor(m => m.MonthlyIncome)
<button type="button" class="btn btn-success submit">Ask</button>
}
<br/><br/>
<div class="alert alert-warning fade">
<img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
<strong><span class="alert-content"></span></strong>
</div>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function openAlert(txt) {
$('.alert-content').text(txt);
$('.alert').addClass('in');
}
function closeAlert() {
$('.alert').removeClass('in');
}
$(function(){
var answer = '@Model.Answer';
if(answer && answer != '')
openAlert(answer);
$('#Question').change(closeAlert);
$('#Question').keyup(closeAlert);
$('.submit').click(function(){
if($('form').valid()) {
$.ajax({
url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {Answer: '', Question: $('#Question').val()},
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp);
}});
}
else {
closeAlert();
}
});
});
</script>
</body>
</html>
我不知道这两个输入之间有什么区别。
我使用的是DataFormat
,因为我希望格式集中在我的模型上。不要使用此代码@string.Format(“{0:N2}”,decimal.Round(agent.MonthlyIncome,2,MidpointRounding.AwayFromZero))
来限制小数位数。因为我会在我所有的观点中这样做,如果这是我所做的
我还尝试只输出月收入的值
<td>@agent.MonthlyIncome</td>
@agent.MonthlyIncome
这仍然返回5位小数。要使用
TextBoxFor()
显示格式化值,请使用
第二个参数是格式字符串。请注意,只有在使用EditorFor()
或DisplayFor()
还请注意,
@Html.DisplayFor(m=>m.MonthlyIncome)
将以正确的格式呈现值。DisplayFormat
仅适用于编辑器for/DisplayFor
。看看小提琴的mvc
型号
public class AgentModel
{
[Display(Name = "Monthly Income")]
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public decimal MonthlyIncome { get; set; }
}
使用制度;
使用System.ComponentModel.DataAnnotations
namespace HelloWorldMvcApp
{
public class SampleViewModel
{
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public decimal MonthlyIncome { get; set; }
//See here for list of answers
public string Answer { get; set; }
}
}
控制器
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var s = new SampleViewModel();
s.MonthlyIncome = 1000;
return View(s);
}
[HttpPost]
public JsonResult GetAnswer(string question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(answer);
}
private static Random _rnd = new Random();
private static List<string> _db = new List<string> { "Yes", "No", "Definitely, yes", "I don't know", "Looks like, yes"} ;
}
}
使用系统;
使用System.Web.Mvc;
使用System.Collections.Generic;
命名空间HelloWorldMvcApp
{
公共类HomeController:控制器
{
[HttpGet]
公共行动结果索引()
{
var s=新的SampleViewModel();
s、 月收入=1000;
返回视图;
}
[HttpPost]
公共JsonResult GetAnswer(字符串问题)
{
int index=_rnd.Next(_db.Count);
var-answer=_db[索引];
返回Json(应答);
}
私有静态随机_rnd=新随机();
私有静态列表_db=新列表{“是”、“否”、“肯定是”、“我不知道”、“看起来像,是”};
}
}
查看
//this input display the two decimal
@Html.EditorFor(m => m.MonthlyIncome, new { htmlAttributes = new { @class = "form-control" } })
//this one display 5 decimal
@Html.TextBoxFor(m => m.MonthlyIncome, new { @class = "form-control"})
@model HelloWorldMvcApp.SampleViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(m => m.Question)
@Html.TextBoxFor(model => model.Question, new {@class="form-control"})
@Html.ValidationMessageFor(model => model.Question)
</div>
@Html.DisplayFor(m => m.MonthlyIncome)
<button type="button" class="btn btn-success submit">Ask</button>
}
<br/><br/>
<div class="alert alert-warning fade">
<img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
<strong><span class="alert-content"></span></strong>
</div>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function openAlert(txt) {
$('.alert-content').text(txt);
$('.alert').addClass('in');
}
function closeAlert() {
$('.alert').removeClass('in');
}
$(function(){
var answer = '@Model.Answer';
if(answer && answer != '')
openAlert(answer);
$('#Question').change(closeAlert);
$('#Question').keyup(closeAlert);
$('.submit').click(function(){
if($('form').valid()) {
$.ajax({
url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {Answer: '', Question: $('#Question').val()},
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp);
}});
}
else {
closeAlert();
}
});
});
</script>
</body>
</html>
@model HelloWorldMvcApp.SampleViewModel
@{
布局=空;
}
引导101模板
.字段验证错误{
颜色:#ff0000;
}
你好,陌生人
@使用(Html.BeginForm())
{
@LabelFor(m=>m.Question)
@Html.TextBoxFor(model=>model.Question,新{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Question)
@DisplayFor(m=>m.monthlyncome)
问
}
函数openAlert(txt){
$('.alert content').text(txt);
$('.alert').addClass('in');
}
函数closeAlert(){
$('.alert').removeClass('in');
}
$(函数(){
var answer='@Model.answer';
如果(回答和回答!='')
openAlert(答案);
$('问题')。更改(closeAlert);
$('问题').keyup(closeAlert);
$('.submit')。单击(函数(){
if($('form').valid(){
$.ajax({
url:'@url.RouteUrl(新的{action=“GetAnswer”,controller=“Home”}),
数据:{回答:'',问题:$('#问题').val()},
键入:“POST”,
数据类型:“json”,
contentType:“应用程序/json;字符集=utf-8”,
成功:功能(resp){
openAlert(resp);
}});
}
否则{
closeAlert();
}
});
});
我明白了…,所以我需要在我拥有的每个视图上添加format参数?其中,如果我使用编辑器for,它将自动在我的模型上添加dataanotation。如果要使用TextBoxFor()
,则选择“是”。但是您不想使用EditorFor()
有什么原因吗?您问题中的两个实现将生成相同的html。您好,steph。。我将使用EditorFor
,因为它在编辑文本框格式时非常有效。。。。然而,如果我试图在我的表中添加此项,我如何显示MonthlyIncome
。MonthlyIncome,因为它仍将显示5位小数,这与使用EditorFor
时不同,它将转换为文本框并转换显示?请参阅我的回答的最后一段如何循环数据。。。我每个月都会收到一大堆的,?