簡體   English   中英

如何在Asp.net MVC4中避免PostBack

[英]How to Avoid PostBack in Asp.net MVC4

我有一個表單,將在兩個不同的下拉列表綁定一些值,我保存用戶選擇的值。現在我使用RequiredIf屬性。它也工作正常。如果用戶錯過選擇值它顯示消息,如同一些方式一些單擊提交按鈕后,下拉列表中的選定值將變為默認值。由於操作結果再次加載,我需要顯示用戶選擇而不改變用戶選項。

我的模型代碼是;

> public ObservableCollection<Receipt> GetReceiptList()
>         {
>             ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
>             DataTable dtReceipt = new DataTable();
>             dtReceipt = objDAL.ExecuteTable(CommandType.StoredProcedure, "sp_Receipt_Select");
>             foreach (DataRow dr in dtReceipt.Rows)
>             {
>                 ReceiptList.Add(new Receipt
>                 {
>                     Id = Convert.ToInt32(dr["REC_Id_I"]),
>                     Cust_Name = dr["CUS_Name_V"].ToString(),
>                     Pay_Amount = dr["REC_PaidAmount_M"].ToString(),
>                     Pay_Mode = dr["REC_PayMode_C"].ToString(),
>                     Bank_Name = dr["REC_BankName_V"].ToString(),
>                     Bank_Address = dr["REC_BankAddress"].ToString(),
>                     ChequeNo = dr["REC_ChequeNo_V"].ToString(),
>                     Cheque_Date = dr["REC_ChequeDate_D"].ToString(),
>                 });
>             }
>             return ReceiptList;
>         }

控制代碼

//AtLoad
public ActionResult ReceiptMaster(Receipt model)
        {
            ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
            Receipt Receipt = new Models.Receipt();
            ReceiptList = Receipt.GetReceiptList();
            ModelState.Clear();
            Sales sales = new Models.Sales();
            DataTable dtCustomer = new DataTable();
            dtCustomer = sales.GetCustomerList();

            IList<Sales> MyCustList = new List<Sales>();
            foreach (DataRow mydataRow in dtCustomer.Rows)
            {
                MyCustList.Add(new Sales()
                {
                    Cust_Id = Convert.ToInt32(mydataRow["Id"].ToString().Trim()),
                    Cust_Name = mydataRow["Name"].ToString().Trim()
                });
            }
            var CustName = new SelectList(MyCustList, "Id", "Cust_Name");
            ViewData["Cu_Name"] = CustName;
            return View(ReceiptList);
        }



    //TO Insert
[HttpPost]
        public ActionResult ReceiptMaster(Receipt model, string command)
        {
            Receipt Receipt = new Models.Receipt();

            if (command == "Sumbit")
            {
                int Id = 0;
                if (model.Pay_Mode == "C")
                {
                    model.ChequeNo = "";
                    model.Cheque_Date = ("1/1/1753 12:00:00 AM");
                    model.Bank_Name = "";
                    model.Bank_Address = "";
                }

                if (ModelState.IsValid)
                {
                    Id = Receipt.SaveReceipt(model.Id, model.Cust_Id, model.Pay_Amount, model.Pay_Mode, model.Bank_Name, model.Bank_Address, model.ChequeNo, model.Cheque_Date);
                    if (Id > 0)
                    {
                        ViewData["Success"] = "Product was saved successfully.";
                        ViewData["ControlView"] = 1;

                        return RedirectToAction("ReceiptMaster", "Admin");

                    }
                    return RedirectToAction("ReceiptMaster", "Admin");
                }

                ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
                ReceiptList = Receipt.GetReceiptList();
                return View(ReceiptList);
            }

            ObservableCollection<Receipt> ReceiptList1 = new ObservableCollection<Receipt>();
            ReceiptList1 = Receipt.GetReceiptList();
            return View(ReceiptList1);

        }

腳本用於DropDown中的綁定值

<script type="text/javascript">

    $(document).ready(function () {
        $.post('@Url.Action("SelectCustomerForDropJson", "Admin")', null, function (data) {
            var select = $("#Cust_Id");
            select.empty();
            select.append($('<option/>', { value: '', text: '--Select--' }));
            $.each(data, function (index, Data) {
                select.append($('<option/>', {
                    value: Data.Value,
                    text: Data.Text
                }));
            });
        });
    });
</script>

我不是100%肯定你在問什么,但聽起來你需要在RequiredIf屬性上啟用客戶端驗證

更改return RedirectToAction("ReceiptMaster", "Admin");

return View(model);

在你的帖子中

如果您使用了RedirectToAction,那么它會加載HTTP GET方法。 所以你的驗證信息已經消失了。

只需復制然后通過我的下面的代碼而不是你的Post動作代碼

並刪除此行: Receipt Receipt = new Models.Receipt(); 調用模型而不是Receipt

//TO Insert
[HttpPost]
        public ActionResult ReceiptMaster(Receipt model, string command)
        {


            if (command == "Sumbit")
            {
                int Id = 0;
                if (model.Pay_Mode == "C")
                {
                    model.ChequeNo = "";
                    model.Cheque_Date = ("1/1/1753 12:00:00 AM");
                    model.Bank_Name = "";
                    model.Bank_Address = "";
                }

                if (ModelState.IsValid)
                {
                    Id = Receipt.SaveReceipt(model.Id, model.Cust_Id, model.Pay_Amount, model.Pay_Mode, model.Bank_Name, model.Bank_Address, model.ChequeNo, model.Cheque_Date);
                    if (Id > 0)
                    {
                        ViewData["Success"] = "Product was saved successfully.";
                        ViewData["ControlView"] = 1;
                          ObservableCollection<Receipt> ReceiptList = new              ObservableCollection<Receipt>();
            ReceiptList = Receipt.GetReceiptList();
            return View(ReceiptList);

                    }
                    ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
            ReceiptList = Receipt.GetReceiptList();
            return View(ReceiptList);
                }

                ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
                ReceiptList = Receipt.GetReceiptList();
                return View(ReceiptList);
            }

            ObservableCollection<Receipt> ReceiptList1 = new ObservableCollection<Receipt>();
            ReceiptList1 = Receipt.GetReceiptList();
            return View(ReceiptList1);

        }

編輯

請為ReceiptList添加一個模型屬性,並在post方法內部分配此屬性中的值,現在僅返回模型(現在這個ReceiptList值存儲在新的ReceiptList屬性中),但是只返回gridview屬性來查看。 但驗證消息和先前的值存儲在模型屬性中,因此您需要在模型中為ReceiptList添加一個屬性,並在此屬性中讀取和寫入網格視圖數據。

現在你將嘗試我的下面代碼(必須看到我的評論,想象一下model.ReceiptList是我們在你的模型中添加一個新屬性)

//TO Insert
[HttpPost]
        public ActionResult ReceiptMaster(Receipt model, string command)
        {


            if (command == "Sumbit")
            {
                int Id = 0;
                if (model.Pay_Mode == "C")
                {
                    model.ChequeNo = "";
                    model.Cheque_Date = ("1/1/1753 12:00:00 AM");
                    model.Bank_Name = "";
                    model.Bank_Address = "";
                }

                if (ModelState.IsValid)
                {
                    Id = Receipt.SaveReceipt(model.Id, model.Cust_Id, model.Pay_Amount, model.Pay_Mode, model.Bank_Name, model.Bank_Address, model.ChequeNo, model.Cheque_Date);
                    if (Id > 0)
                    {
                        ViewData["Success"] = "Product was saved successfully.";
                        ViewData["ControlView"] = 1;
                          ObservableCollection<Receipt> ReceiptList = new              ObservableCollection<Receipt>();
             model.ReceiptList = Receipt.GetReceiptList();// model.ReceiptList is your model property
            return View(model);

                    }
                    ObservableCollection<Receipt> ReceiptList = new              ObservableCollection<Receipt>();
             model.ReceiptList = Receipt.GetReceiptList();// model.ReceiptList is your model property
            return View(model);
                }

                ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
                ReceiptList = Receipt.GetReceiptList();
                return View(ReceiptList);
            }

             ObservableCollection<Receipt> ReceiptList = new              ObservableCollection<Receipt>();
             model.ReceiptList = Receipt.GetReceiptList();// model.ReceiptList is your model property
            return View(model);

        }

在模型類中添加屬性,例如

ObservableCollection<Receipt> ReceiptList  {get :set;}

以下代碼可防止%100回發,只需嘗試即可。

您需要使用Json以防止在頁面中完全回發。 之后,您必須返回部分視圖。

例如;

HTML代碼:

<input type="text" id="UserName" name="UserName"/>
<input type="button" onclick="ButonClick()" value="Enter"/>

Javascript代碼:

function ButonClick() {
var data= {
UserName: $('#UserName').val(),
};
$.ajax({
url: "/Home/MyActionResult",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data),

控制器:

public ActionResult MyActionResult(string UserName,MyModel model)
{
var stringView = RenderRazorViewToString("_YourPartialView", model);
return Json(stringView, JsonRequestBehavior.AllowGet);
}

注意:

您需要以下代碼來呈現json的局部視圖。

以下添加到您的控制器。

public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData,    TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM