Проверить, выбрана ли строка MVC 3 - PullRequest
0 голосов
/ 04 октября 2011

В моем проекте MVC 3 я использую довольно странный фрагмент кода для выбора строки в таблице и выполнения некоторых обновлений. Моя проблема в том, что я не уверен, как проверить, была ли выбрана строка.

Вот код, на мой взгляд:

<p><i>Select an invoice from the grid below:</i></p>

@if (!string.IsNullOrEmpty(TempData["PaymentError"] as string))
{
<div id="error" style="margin: 0 auto; width: 400px;">
    <p style="width: 400px;"><img src="../../Content/images/errorsm.png" style="vertical-align: middle; padding: 5px;"/><span style="color: #A62000;font-weight: bold;">@(TempData["PaymentError"] as string)</span></p>
</div>
}

<table id="database">
<tr>
<th></th>
    <th>
        Invoice Number
    </th>
    <th>
        Invoice Amount
    </th>
    <th>
        Invoice Month
    </th>
    <th>
        Invoice Status
    </th>
    <th>
        Client
    </th>
    <th></th>
</tr>
@using (Html.BeginForm("Confirm", "Invoice"))
{

foreach (var item in Model)
{
    string selectedRow = "";
    if (item.InvoiceNumberID == ViewBag.InvoiceNumberID)
    {
        selectedRow = "selectedRow";
    } 

<tr class="@selectedRow" valign="top">
            <td> 
           <a href='javascript:void(0)' class='select' data-id=@item.InvoiceNumberID >Select</a>


        </td> 
     <td>
        @Html.DisplayFor(modelItem => item.InvoiceNumberID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.InvoiceAmount)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.InvoiceMonth)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.InvoiceStatus)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Client.FullName)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.InvoiceNumberID }) |
        @Html.ActionLink("Details", "Details", new { id = item.InvoiceNumberID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.InvoiceNumberID })
    </td>

</tr>

}
<input type='hidden' id='id' name='id' value='0' />

<p>
<a href='@Url.Action("CreateBulkInvoices", "Invoice")'>Generate Invoices</a>
</p>
<table>
<br />
<i>Select an amount below to confirm as paid:</i><br /><br />
<tr><td><b>Monthly Amounts:</b></td><td><b>Weekly Amounts:</b></td></tr>
<tr><td>Private Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "640", true) R640.00<br /></td><td>Private Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "140", true) R160.00<br />    </td></tr>
<tr><td>Private Lesson (1/2 Hour) @Html.RadioButton("InvoiceAmount", "350", true) R350.00<br /></td><td>Private Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "87.50", true) R87.50<br /></td></tr>
<tr><td>Group Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "460", true) R460.00</td>  <td>Private Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "115", true) R115.00<br /></td></tr>
<tr><td>Custom Amount @Html.RadioButton("InvoiceAmount", "115", true)    @Html.TextBox("InvoiceCustomAmount")<br /></td></tr>
</table> 
<br />
<p><i>Select a payment type:</i>
</p> 
<p>@Html.RadioButton("PaymentType", "EFT", true) EFT<br />
@Html.RadioButton("PaymentType", "Credit Card", true) Credit Card<br />
@Html.RadioButton("PaymentType", "Cheque", true) Cheque


</p>                                                         
<p><input type="submit" value="Confirm" /></p>       
}
</table>
<br />



<script type='text/javascript'>
    $('.select').click(function(){
        $('#id').val($(this).attr('data-id'));
        $(this).closest('table').find('tr').removeClass('selectedRow');
        $(this).closest('tr').addClass('selectedRow');
             });
</script>

И код в моем контроллере:

public ActionResult Confirm(int id, long InvoiceAmount, string PaymentType, float? InvoiceCustomAmount)
    {
        var invoice = db.Invoice.Find(id);

        //now validate that if the logged in user is authorized to select and confirm this invoice or not.
        var clientPayment = new ClientPayments();

        clientPayment.InvoiceNumberID = id;

        if (InvoiceAmount == 115)
        {
            InvoiceAmount = (long)InvoiceCustomAmount;
        }

        var TotalPayments = invoice.ClientPayments.Sum(payment => payment.PaymentAmount) + InvoiceAmount;

        if (TotalPayments > invoice.InvoiceAmount)
        {
            TempData["PaymentError"] = "You cannot pay more than the invoice amount";
            return RedirectToAction("Index");
        }


        clientPayment.PaymentAmount = InvoiceAmount;

        clientPayment.PaymentType = PaymentType;
        clientPayment.PaymentDate = DateTime.Now;
        db.ClientPayments.Add(clientPayment);

        if (TotalPayments != invoice.InvoiceAmount)
        {
            invoice.InvoiceStatus = "Partly Paid";
        }
        else
        {
            invoice.InvoiceStatus = "Confirmed";
        }

        // You don´t need this, since "invoice" was retrieved earlier in the method the database context
        // knows that changes have been made to this object when you call "SaveChanges".
        // db.Entry(invoices).State = EntityState.Modified;

        db.SaveChanges();

        return View();
    }

Есть ли простой способ проверить, была ли выбрана строка при отправке формы?

Спасибо, Amy

1 Ответ

0 голосов
/ 04 октября 2011

Итак, как насчет того, чтобы не включить кнопку отправки, если вы на самом деле не выбрали что-то?Вы можете изначально установить кнопку отправки, чтобы отключить.Примерно так:

<input type="submit" value="Confirm" class="mysubmit" />

$(document).ready(function () {
   $('.mysubmit').attr('disabled', 'disabled');

   // whatever else...
});

Повторное включение можно сделать, удалив этот атрибут:

$('.mysubmit').removeAttr('disabled');

Возможно, вы могли бы изменить click, чтобы сделать это:

<script type='text/javascript'>
    $('.select').click(function(){
        $('#id').val($(this).attr('data-id'));
        $(this).closest('table').find('tr').removeClass('selectedRow');
        $(this).closest('tr').addClass('selectedRow');
        // enable your submit button
        $('.mysubmit').removeAttr('disabled');
    });
</script>

Не проверял, но, похоже, это гарантирует, что пользователь нажал ссылку класса select, прежде чем нажать кнопку отправки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...