简体   繁体   English

如何在Asp.net MVC4中避免PostBack

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

I have a form in that in will bind Some values on two differnt dropdown,and i save the users selected value.Now i use RequiredIf attributes.Its also works fine.If user missed to select value it shows messages, as the same way some selected values in dropdown will comes to default after submit button was clicked.I need to show meesages without any change in users selection because of Action Results Loads Again. 我有一个表单,将在两个不同的下拉列表绑定一些值,我保存用户选择的值。现在我使用RequiredIf属性。它也工作正常。如果用户错过选择值它显示消息,如同一些方式一些单击提交按钮后,下拉列表中的选定值将变为默认值。由于操作结果再次加载,我需要显示用户选择而不改变用户选项。

My Code for Model is; 我的模型代码是;

> 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;
>         }

Code for Control 控制代码

//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);

        }

Script Used for Bind values in DropDown 脚本用于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属性上启用客户端验证

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

return View(model);

in your post action 在你的帖子中

if you used the RedirectToAction ,then it's load the HTTP GET Method . 如果您使用了RedirectToAction,那么它会加载HTTP GET方法。 So your validation message was gone . 所以你的验证信息已经消失了。

Just copy then past my below code instead of your Post action code 只需复制然后通过我的下面的代码而不是你的Post动作代码

and remove this line : Receipt Receipt = new Models.Receipt(); 并删除此行: Receipt Receipt = new Models.Receipt(); and call model instead of 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);

        }

Edit 编辑

Please add one model property for ReceiptList and assign the values in this property in inside of your post method and now return the model only (Now this ReceiptList values in stored in your newly ReceiptList property) ,But you are return just your gridview property to view. 请为ReceiptList添加一个模型属性,并在post方法内部分配此属性中的值,现在仅返回模型(现在这个ReceiptList值存储在新的ReceiptList属性中),但是只返回gridview属性来查看。 But the validation message and previous values are stored in your model properties, So you need to add one property for ReceiptList in your model , and read and write the grid view data in this property . 但验证消息和先前的值存储在模型属性中,因此您需要在模型中为ReceiptList添加一个属性,并在此属性中读取和写入网格视图数据。

Now You will try my Below code (must see my comments ,Just imagine for model.ReceiptList is we add a new property in your model) 现在你将尝试我的下面代码(必须看到我的评论,想象一下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);

        }

Add a property in your model class, like 在模型类中添加属性,例如

ObservableCollection<Receipt> ReceiptList  {get :set;}

Below codes prevent %100 postback , just try. 以下代码可防止%100回发,只需尝试即可。

You need to use Json in order to prevent full postback in your page. 您需要使用Json以防止在页面中完全回发。 After that you must return to Partial View. 之后,您必须返回部分视图。

As instance; 例如;

HTML Code: HTML代码:

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

Javascript Code: Javascript代码:

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

Controller: 控制器:

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

Note: 注意:

You need below code to render your partial view for json. 您需要以下代码来呈现json的局部视图。

Add below to your controller too. 以下添加到您的控制器。

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