2012-12-10 3 views
0

C#에서 asp.net 면도기를 사용하고 있습니다. 입력 된 값이 통화인지 확인하려고하지만 올바르게 수행 할 수 없습니다.AddModelError가 컨트롤러로 다시 전달되지 않음 (업데이트 됨)

@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를 호출하고이 뷰의 시작에 수표 하였다 :

이 내 선불보기

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

입니다 :

이 내 PaymentModel에

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

PrePayment에서 AddModelEr에서 보낸 내 오류를 다시받을 수없는 것 같습니다. 너. 나는 그것을 변경 :

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); 
} 
+0

리디렉션 때문입니다. – SLaks

+0

오류는 무엇입니까? –

+0

View를 시도했지만 컨트롤러를 호출하지 않았습니다. 컨트롤러에 연락하여 오류를 전달하려면 어떻게해야합니까? – ErocM

답변

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; 
+0

그게 ... 내가 잘못하고있는 것에 대한 설명과 그것을 고치는 법에 대한 좋은 예입니다! 도와 줘서 고마워 !!! – ErocM

0

것은 당신이 당신의 재산에 데이터 주석을 추가하고 유효성을 검사하는 ModelState.IsValid 속성을 사용해야 할 수 있음 일을 보낼 경우는 POST 방법에서

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

, 유효성 검사 통과 여부를 확인 다시 뷰로 모델링하십시오.

[HttpPost] 
public ActionResult SendPayment(PrePayment model) 
{ 
    if(ModelState.IsValid) 
    { 
    //do the fun stuff 
    } 
    return View(model); 
} 
+0

내가보기 만 반환하면 PrePayment로 돌아가서 그것이 지금있는 곳으로 되돌려 보내려고합니다. 그러나 뷰를 호출하려고 할 때 모델을 보냈습니다. 내가 위의 코드를 수정했습니다. – ErocM

+0

업데이트 해 주셔서 감사하지만 "필드 지불 금액 : 0.01 - 9000000 사이 여야합니다."와 같은 메시지가 표시됩니다. 내게 어색해 보이는 군. 또한 양식이 시작 되 자마자 메시지가 표시됩니다. – ErocM

+0

데이터 주석의 오류 메시지를 사용자 정의 할 수 있습니다. 로드 중 페이지의 유효성을 검사하고 있습니까? – Shyju

관련 문제