Tips to Prevent PostBack in Asp.net MVC4

I have a form where I need to bind some values to two different dropdowns and save the user's selected value. I am using RequiredIf attributes, which work fine. However, if the user forgets to select a value, an error message is shown. The issue arises when some selected values in the dropdown reset to default after the submit button is clicked due to the Action Results loading again. I need to display messages without any changes in the user's selection.

Here is my code for the Model:

> 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 Binding Values in 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>

Answer №1

Modify your post action by replacing

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

return View(model);

Using RedirectToAction loads the HTTP GET Method which causes the validation message to disappear.

Simply paste the code below into your Post action code

and delete this line:

Receipt Receipt = new Models.Receipt();
and use the model instead of 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 a model property for ReceiptList and assign values inside your post method. Return the model only (now ReceiptList values are stored in your newly added ReceiptList property). Previously, you were returning only your gridview property to view. Add one property for ReceiptList in your model to store and retrieve the grid view data.

Try out the modified code below (considering model.ReceiptList as the newly added property in your model)

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

Answer №2

I'm a bit unsure about the exact nature of your question, but it seems like you may be looking to implement client-side validation for your RequiredIf attribute.

Answer №3

These snippets of code will help you achieve seamless loading without a full postback.

To prevent unnecessary page reloads, utilize JSON and partial views in your development process - follow this example:

Here is an example:

HTML Code:

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

Javascript Code:

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 the following code to render your partial view for JSON rendering purposes.

Add the following snippet to your controller as well.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an SVG image is embedded, its color may not change even after being converted to an inline SVG

I've inserted an SVG using an img tag. When hovering over it, I want the fill color of the SVG to change. I attempted to convert the SVG to inline SVG following this method, but it doesn't seem to be working as expected. No console errors are b ...

What is the best way to make text span across multiple columns in a table?

Spanning column text across 3 columns of a grid (table) is my current challenge. I want the text to begin in the 3rd column and wrap around to the end of the 5th column. I successfully managed to span it by applying a CSS style to the 3rd column's cl ...

Transforming JSON into a two-dimensional format using React Native

I received JSON data as a response from the API in the following format:- JSON=[ { product:{"final_price": 500,"customers_basket_quantity": 3,"products_id": 123, "products_name": 'cotton'}, attribut ...

Efficient Reusability with RAZOR MVC3 Partial Views

Looking to display two entities, PopularTutorial and Blog, on the homepage with the option for reuse in other views. The "PopularTutorial" section includes manual paging - clicking page 1 shows the first 3 popular tutorials, while clicking page 2 displays ...

Troubleshooting Problems with File Upload Response in ASP.Net MVC Ajax.BeginForm

I have implemented a modal feature that allows users to upload a file. I am looking for a JSON response to indicate whether the upload was successful or not, and then display this information to the end user. Here is my current View: @model int <div ...

When using ui-router in AngularJS, the page refuses to scroll to a specific ID if its hash is already present in the URL

Having trouble with hash-id linking using ui-router in AngularJS. When the URL already contains the desired hash (e.g., whatever.com/#/route1#des1) and an anchor tag with a link to #des1 is clicked, the link does not work and the page does not scroll down ...

Steps for transforming a nested JSON object into XML format with XSLT

<root><dataResponse>{"status":"C","responseCode":200,"description":"Success","resultsInformation":[{&... For the complete content, please refer to the original text. This is my xml co ...

Tips for discreetly recording information without disrupting normal workflow until necessary

Every 100-200 uses, I encounter a strange bug that I just can't seem to reproduce consistently. It's not a top priority to fix, but I would like to address it. To investigate further, I would need to scatter about 30 console.log statements throu ...

Accessing the Div id stored in a session parameter

Is there a way to store the id (div id) into a session variable? This is an example of my code below: <div class='fieldRow'>Options </div> <div id="abcde"></div> <div class='Row'> <?php $user_typ ...

Transforming a Python list into a JavaScript array

Hey there, I'm in the process of creating a JavaScript array of dates to input into a jQuery datepicker addon. Here is my Django view: def autofill_featured(request): show_id = request.GET.get('show_id') show = Show.objects.get(id=s ...

Implementing a specific block of code once an Angular service successfully retrieves data from the server and finishes its operations

Within the service: appRoot.factory('ProgramsResource', function ($resource) { return $resource('Home/Program', {}, { Program: { method: 'get', isArray: false } }) }); Inside the controller: appRoot.controller('Pro ...

VueJS added a new object to the array, but the data did not update reactively

Here is my current data layout days: [ { id: 0 name: 'Monday', times: [] }, { id: 1 name: 'Tuesday', times: [] } } I have implemented the following function to append an object to the times array. onT ...

Once logged out in Vue Router, the main app template will briefly display along with the login component

After clicking the logout button, I am experiencing an issue where my main UI remains visible for a few seconds before transitioning to a blank page and displaying the login form component. This behavior is occurring within the setup of my App.vue file: & ...

Determine the quantity of objects stored in MongoDB

What is the best way to retrieve a total count of all items in a MongoDB collection with the 2.x C# driver? I have attempted to utilize the CountAsync method, but it requires passing in a filter. Is there a way to retrieve all items without applying a fil ...

Tips for extracting a portion of a string in JavaScript:

I'm dealing with a string that looks like this: var str1="tag:youtube.com,2008:video:VrtMalb-XcQ"; I want to extract the last part of the string, which is VrtMalb-XcQ. What's the best way to do this? ...

Creating auto serial numbers in the MERN stackWould you like to know how to

I need help coming up with a way to automatically generate serial numbers for my "ticketno" field. Every time a user creates a new application ticket, the ticket number should increment by one. Can someone guide me on how to achieve this? This i ...

What is the best way to implement gravity in order to make my character jump effectively

As a beginner in the world of coding, I am currently working on creating a game. However, one major challenge I am facing is simulating gravity to make my character jump effectively. Despite trying various methods, I have encountered disappointing results. ...

The issue arises when attempting to make an Ajax request after changing the value of a cascading dropdown

Hey there! I'm currently working on a cascading drop-down feature where, upon change, I need to populate another field with data from the database. Unfortunately, every time I try to populate the drop-down, my AJAX call returns an error 500. I can&ap ...

Move the text below the fixed header position

Here is a fiddle I created to address the issue mentioned: link here In this scenario, the header and footer are positioned absolutely with 100% width, while the middle content consists of a dashboard table. The header contains two images that when clicke ...

Is it possible to receive both errors and warnings for the same ESLint rule?

My team is currently in the process of refactoring our codebase, utilizing ESLint to pinpoint any lint errors within our files. Initially, we set high thresholds in one .eslintrc file and have been gradually decreasing these limits as we enhance specific f ...