0

C# で asp.net Razor を使用しています。入力した値が通貨であることを確認しようとしていますが、正しく確認できないようです。

これは私のPaymentModelにあります:

  [Required]
  [DataType(DataType.Currency)]
  [DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
  [Display(Name = "Payment Amount:")]
  public decimal Amount { get; set; }

これは私の前払いビューです:

@model SuburbanCustPortal.Models.PaymentModel.PrePayment

@{
    ViewBag.Title = "Make a payment!";
}

<script>
$(function(){
  $("#AccountId").change(function(){
    var val=$(this).val();
    $("#currentBalance").load("@Url.Action("GetMyValue","Payment")", { custid : val });
    document.forms[0].Amount.focus();
  });
});
</script>

<h2>Make a Payment</h2>

  @using (Html.BeginForm("SendPayment", "Payment", FormMethod.Post))
  {
    @Html.ValidationSummary(true, "Please correct the errors and try again.")
    <div>
      <fieldset>
        <legend>Please enter the amount of the payment below:</legend>

        <div class="editor-label">
          Please select an account.
        </div>

        @Html.DropDownListFor(x => x.AccountId, (IEnumerable<SelectListItem>)ViewBag.Accounts)

        <div class="editor-label">
          @Html.LabelFor(m => m.AccountBalance)
        </div>
        <div class="editor-field">
          <label class="sizedCustomerDataLeftLabel" id="currentBalance">@Html.DisplayFor(model => model.AccountBalance)&nbsp;</label>
        </div>      

        <div class="editor-label">
          @Html.LabelFor(m => m.Amount)
        </div>
        <div class="editor-field focus">
          @Html.TextBoxFor(m => m.Amount, new { @class = "makePaymentText" })
          @Html.ValidationMessageFor(m => m.Amount)
        </div>

        <p>
          <input id="btn" class="makePaymentInput" type="submit" value="Pay Now"  onclick="DisableSubmitButton()"/>  
        </p>
      </fieldset>
    </div>
  }

This is my Prepayment ActionResult:

    [Authorize]
    public ActionResult PrePayment(PaymentModel.PrePayment model)
    {
      var list = new List<SelectListItem>();
      var custs = _client.RequestCustomersForAccount(User.Identity.Name);
      foreach (var customerData in custs)
      {
        var acctno = customerData.Branch + customerData.AccountNumber;
        var acctnoname = string.Format(" {0} - {1} ", acctno, customerData.Name);
        // msg += string.Format("*** {0} - {1} ***{2}", customerData.AccountId, acctnoname, Environment.NewLine);
        list.Add(new SelectListItem() { Text = acctnoname, Value = customerData.AccountId });
      }

      if (custs.Length > 0)
      {
        model.AccountBalance = String.Format("{0:C}", Decimal.Parse(custs[0].TotalBalance));
      }

      ViewBag.Accounts = list;
      return View(model);
    }

ビューの投稿はSendPaymentを呼び出します。これはビューの最初の私のチェックでした:

    if (model.Amount == 0)
    {    
      ModelState.AddModelError("Amount", "Invalid amount.");
      return RedirectToAction("PrePayment", model);
    }

AddModelError から送信したエラーを PrePayment で取得できないようです。私はそれを次のように変更しました:

    if (model.Amount == 0)
    {    
      ModelState.AddModelError("Amount", "Invalid amount.");
      return View("PrePayment", model);
    }

しかし、期待しているデータがないため、コントローラーを呼び出すことはなく、画面でエラーが発生します。

エラーのある呼び出しビューにリダイレクトするにはどうすればよいですか?

==== 追加情報 ====

ここに私の前払いビューがあります:

[Authorize]
public ActionResult PrePayment(PaymentModel.PrePayment model)
{
    var list = new List<SelectListItem>();
    var custs = _client.RequestCustomersForAccount(User.Identity.Name);
    foreach (var customerData in custs)
    {
      var acctno = customerData.Branch + customerData.AccountNumber;
      var acctnoname = string.Format(" {0} - {1} ", acctno, customerData.Name);
      // msg += string.Format("*** {0} - {1} ***{2}", customerData.AccountId, acctnoname, Environment.NewLine);
      list.Add(new SelectListItem() { Text = acctnoname, Value = customerData.AccountId });
    }

    if (custs.Length > 0)
    {
      var amt =String.Format("{0:C}", Decimal.Parse(custs[0].TotalBalance));
      model.AccountBalance = amt;
      decimal namt;
      if (decimal.TryParse(amt.Replace(",",string.Empty).Replace("$", string.Empty), out namt))
      {
        model.Amount = namt;
      }
    }
  ViewBag.Accounts = list;
  return View(model);
}
4

2 に答える 2

2

取り組む必要のある問題がいくつかあります。

1.  return View("PrePayment", model);  
This will not call the controller, as the function name suggests, it only passing your object to the specified "View"(.cshtml file)

2.     return RedirectToAction("PrePayment", model);  
You will not persist modelstate data, because you are doing a redirect.

問題を解決する推奨ワークフロー。少なくともそれは私のものを解決しました。

1. Get the form to post to "PrePayment" instead of SendPayment and you will create a new method with the following signature and have all you validation logic in the method
[Authorize]
[HttpPost]
public ActionResult PrePayment(PaymentModel.PrePayment model)

2. If everything goes well then redirect to the success/send payment page depending on your requirement

3. If somehow you need to pass model object onto the next action. Use TempData like following. This will temporarily persist the data till the next action. Then it get disposed:
TempData["payment"]=model;
于 2012-12-11T02:55:16.813 に答える
0

プロパティにデータ注釈を追加し、プロパティを使用ModelState.IsValidして検証する必要があるかもしれません

[Required]
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
[Display(Name = "Payment Amount:")]
[Range(0.01, Double.MaxValue)]
public decimal Amount { get; set; }

メソッドで、POST検証に合格したかどうかを確認し、そうでない場合はモデルをビューに送り返します。

[HttpPost]
public ActionResult SendPayment(PrePayment model)
{
  if(ModelState.IsValid)
  {
     //do the fun stuff
  }
  return View(model);
}
于 2012-12-10T21:00:14.960 に答える