如何在 Asp.net MVC4 中避免回发

Posted

技术标签:

【中文标题】如何在 Asp.net MVC4 中避免回发【英文标题】:How to Avoid PostBack in Asp.net MVC4 【发布时间】:2013-10-03 16:10:54 【问题描述】:

我有一个表单,它将在两个不同的下拉列表中绑定一些值,并且我保存用户选择的值。现在我使用 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>

【问题讨论】:

【参考方案1】:

我不是 100% 确定你在问什么,但听起来你需要 enable client side validation on your RequiredIf attribute。

【讨论】:

【参考方案2】:

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

return View(model);

在您的帖子操作中

如果您使用了 RedirectToAction ,那么它会加载 HTTP GET 方法。所以你的验证信息不见了。

只需复制下面的代码,而不是您的发布操作代码

并删除这一行:Receipt Receipt = new Models.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添加一个属性,并在这个属性中读写网格视图数据。

现在您将尝试我的以下代码(必须查看我的 cmets,想象一下 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;

【讨论】:

先生很好...但是我使用了相同形式的网络网格,所以它会在绑定时显示错误。 我想在模型中分配 ReceiptList 的数据类型 ObservableCollection ReceiptList get :set; 再次查看我的答案 sir find any for this..How to Avoid PostBack in Asp.net MVC4【参考方案3】:

下面的代码可以防止 %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();


【讨论】:

以上是关于如何在 Asp.net MVC4 中避免回发的主要内容,如果未能解决你的问题,请参考以下文章

在 asp.net webform 中单击按钮时避免回发

回发后 F5 的 asp.net 问题,因为它做了它应该做的事情

如何使用带有 asp.net 的 jQuery 进行 onclientclick 回发

如何在回发 ASP.Net Core 后保持选项卡处于活动状态

如何使用javascript在asp.net上停止正在进行的回发(长时间运行)?

在ASP.NET MVC4中如何执行远程验证?