ASP.NET MVC Core Code Firstプロジェクトでは、正常に表示されているfloat型のSaleAmountというプロパティを持つモデルがありますこのプロパティを使用してデータを保存すると、SQL Serverデータベースでこのフィールドがnullとして取得されます。デバッグモードで、私はこの行にブレークポイントを配置するときoAnnualSales.SaleAmount = item.SaleAmount;
コントローラ(下に表示)私はitem.SaleAmount
がnullであることがわかります。ASP.NET MVCモデルで表示モードとデータ保存の両方で通貨フォーマットを使用する方法
ビュー:
public class AnnualSale
{ @model IList<MyProj.Models.SaleViewModel>
<div class="row">
<div class="col-md-9">
<form asp-controller="DbRelated" asp-action="UpdateSales" asp-route-returnurl="@ViewData[" ReturnUrl"]" method="post">
<table class="table">
<thead>
<tr>
<th></th>
<th>
State Name
</th>
<th>
Sale Amount
</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>@Html.HiddenFor(r => r[i].StateId)</td>
<td>
@Html.EditorFor(r => r[i].StateName)
</td>
<td>
@Html.EditorFor(r => r[i].SaleAmount)
</td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-default">Save</button>
</form>
</div>
</div>
[Key]
public int Sale_Id { get; set; }
public int? FiscalYear { get; set; }
[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
public float? SaleAmount { get; set; }
public int StateId { get; set; }
public StateName StateName { get; set; }
}
モデル:
public class AnnualGrant
{
[Key]
public int Sale_Id { get; set; }
public int? FiscalYear { get; set; }
[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
public float? SaleAmount { get; set; }
public int StateId { get; set; }
public StateName StateName { get; set; }
}
コントローラー:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateSales(List<SaleViewModel> model, string returnUrl = null)
{
if (ModelState.IsValid)
{
foreach (var item in model)
{
var oAnnualSales = _context.AnnualSales.Where(r => r.StateId.Equals(item.StateId)).FirstOrDefault();
if (oAnnualSales != null)
{
oAnnualSales.FiscalYear = item.FY;
oAnnualSales.SaleAmount = item.SaleAmount;
}
else
{
AnnualSale oAnnualSaleNew = new AnnualSale { StateId = item.StateId, FiscalYear = item.FY, SaleAmount = item.SaleAmount};
_context.Add(oAnnualSaleNew);
}
}
await _context.SaveChangesAsync();
return View(model);
}
// If we got this far, something failed, redisplay form
return View();
}
I:
が次にあなたがApplication_Startメソッドにそれを追加することによって、MVCバインダーにこれを追加する必要がありますすでにあなたの[前の質問](http://stackoverflow.com/questions/39600688/data-annotation-for-currency-format-not-working)で説明しました。 '' $ 1,000.00 ''という値を投稿すると、 'DefaultModelBinder'によって' float'に束縛されません( '' "1000.00"の値だけが束縛されます)。カスタムのModelBinderを作成する必要があります –