@{ var purpose = CommonMethod.getPurpose(""); for(int i=0;i<10 && i@pur" />
      @{ var purpose = CommonMethod.getPurpose(""); for(int i=0;i<10 && i@pur" />
        @{ var purpose = CommonMethod.getPurpose(""); for(int i=0;i<10 && i@pur"/>

        TechQA.

        Updating div content after submiting ajax form in asp.net MVC3

        4.5k views Asked by user At 2012-08-03T08:07:41+00:00 03 August 2012 at 08:07 2025-12-17T19:14:20+00:00
        <div id="myDiv">
            <ul class="purpose">
            @{ 
                var purpose = CommonMethod.getPurpose("");
                for(int i=0;i<10 && i<purpose.Count();i++)
                {
                    <li><a href="#" >@purpose[i].Text</a></li>
                }
             }
            </ul>
        </div>
        

        on selecting the above single purpose from list it will show below ajax form for updation

        @using (Ajax.BeginForm("UpdatePurpose", "Admin", new AjaxOptions { UpdateTargetId = "updateDiv" }))
        {
            <div  class="profile">
            @Html.Hidden("PurposeID")
            <table>
        
                <tr>
                     <td>Purpose</td>
                     <td>:</td>
                     <td> width="30%">@Html.TextBox("Description")</td>         
                </tr>
                <tr>
                    <td>Admin Password</td>
                    <td>:</td>
                    <td>@Html.Password("Passwd1")</td>
                </tr>
            </table>
           <input type="submit"  value="submit" />
           </div>
        }
        

        After Subting below action is called

        [HttpPost]
        public ActionResult UpdatePurpose(string PurposeID,string Description, string Passwd1)
        {
        
            if (Request.IsAjaxRequest())
            {
                if (!Membership.ValidateUser(User.Identity.Name, Passwd1))
                {
                    ModelState.AddModelError("", "Invalid Admin Password");
                }
                if (ModelState.IsValid)
                {
                    var id = Convert.ToByte(PurposeID);
                    var pur = db.Purposes.Where(p => p.PurposeID == id).SingleOrDefault();
                    pur.Description = Description;
        
                    db.SaveChanges();
                    ViewBag.Result = "Data Updated Successfully.";
                    return View();
                }
            }
            return View();
        }
        

        On submitting above ajax form Updatepurpose I want to show validation message errors if admin password is invalid and also I want to load myDiv content if modelstate is valid and give successful updation message to user

        asp.net-mvc razor updatepanel asp.net-mvc-validation asp.net-mvc-ajax
        Original Q&A
        1

        There are 1 answers

        5
        Shyju Shyju On 2012-08-03T13:23:57+00:00 03 August 2012 at 13:23 BEST ANSWER

        Remove the Ajax.BeginForm HTML Helper and do some handwritten jQuery code. You can do any kind of customization then.

        I would keep your Markup like this (removed AjaxForm, Used a normal form declaration, Added a css class name to submit button)

        <div  class="profile">
        <form>
        @Html.Hidden("PurposeID")
        <table>
            <tr>
                 <td>Purpose</td>
                 <td>:</td>
                 <td> width="30%">@Html.TextBox("Description")</td>         
            </tr>
            <tr>
                <td>Admin Password</td>
                <td>:</td>
                <td>@Html.Password("Passwd1")</td>
            </tr>
        </table>
        <input type="submit" value="submit" class="btnSavePurpose" />
        

        And add some javascript like this

        <script type="text/javascript">
         $(function(){
        
            $(".btnSavePurpose").click(function(e){
               e.preventDefault();
               var item=$(this);
               $.post("@Url.Action("UpdatePurpose","Admin")", 
                                 item.closest("form").serialize(), function(data){
                   if(data.Status=="Success")
                   {
                     //Let's replace the form with messsage                
                     item.closest(".profile").html("Updated Successfully");
                   }    
                   else
                   {
                      alert(data.ErrorMessage);
                   }
        
               });   
            });   
        
         });
        
        </script>
        

        Now update your Action method to return the JSON data

        [HttpPost]
        public ActionResult UpdatePurpose(string PurposeID,string Description, string Passwd1)
        {        
            if (Request.IsAjaxRequest())
            {
                if (!Membership.ValidateUser(User.Identity.Name, Passwd1))
                {
                    return Json( new { Status="Error",
                                       ErrorMessage="Invalid Admin Password"});
                }
                if (ModelState.IsValid)
                {
                    var id = Convert.ToByte(PurposeID);
                    var pur = db.Purposes.Where(p => p.PurposeID == id).SingleOrDefault();
                    pur.Description = Description;
        
                    db.SaveChanges();
                    return Json( new { Status="Success"});
                }
            }
            return View();
        }
        

        What it is doing is, When user clicks on the button with that CSS class, it will serialize the container form and send it to the Action method. Then the action method do its job and if the Validation fails, It will send a JSON in the below format back to the client

         { "Status": "Errorr", "ErrorMessage": "Invalid Admin Password"}
        

        If it is fine, It will do the DB update and send a JSON back to the client in this format.

         { "Status": "Success"}
        

        And in the callback of out ajax(POST) function, we are checking the value of Status in the JSON and showing appropriate message to the user.

        Simple & Clean :)

        Related Questions in ASP.NET-MVC

        • I have a problem outputing the roles on the page ListRoles.cshtml
        • Dropdown list showing SQLServer2005SQLBrowserUser$DONSERVER instead of Active Directory group name in ASP.NET MVC C#
        • Hosting ASP.NET MVC application on IIS web server using Windows 2019 server
        • How to display only department fields associated with a selected department in student automation system?
        • How to send select input data for form submission?
        • Multi level project reference using dll
        • How to upload file to Onedrive using ASP.NET MVC?
        • ASP.NET MVC web app looping between fields only on some devices
        • Is there any automatic job to load AD-groups?
        • How to restrict admin js files to download
        • Download PDF in ASP.NET MVC application
        • How to add bootstrap theme/example into ASP.NET MVC 5?
        • Web API works with Windows authentication enabled when consumed via Swagger but throws an unauthorized issue when accessed through web app
        • ASP.Net Core 7.0 Web App (Model-View-Controller) ErrorViewModel OnGet OnPost do not get called or executed
        • OAuth 2.0 keep getting Authorization has been denied for this request

        Related Questions in RAZOR

        • I have a problem outputing the roles on the page ListRoles.cshtml
        • ASP.NET Core MVC : NullReferenceException: Object reference not set to an instance of an object
        • Blazor/Razor resolve components using dependency injection
        • Receiving 400 bad request on post when customer auth handler is used
        • Prevent modal from popping up when freeze button is clicked
        • AJAX Requests from jQuery to ASP.NET Core API Losing Authentication
        • Initialize a singleton from cookies for a ASP.NET Core Razor project
        • Razor.RuntimeCompilation creates an error
        • ASP.NET Core MVC invoke function through button on razor page
        • Runtime Compilation of Razor Pages Does Not Work .NET 8 VS2022
        • Why does my ASP.NET Core MVC application add some identifier to HTML elements?
        • Question | Visual Studio Code Editor .cshtml file not working properly
        • Error in Using references with Blazor Client
        • JQuery accordion not working in Razor page
        • Challenge with ASP.NET Web Forms to .NET 8 Razor Pages Migration on Private Server

        Related Questions in UPDATEPANEL

        • replace UpdatePanel with telerik
        • Pop-up and download zip file in ASP.NET
        • UpdatePanel and Javascript Issue
        • ASP.NET C# Update Panel, File Upload Control and maintaining and saving information on postback
        • UpdatePanel AsyncPostbackTrigger not firing
        • How to RegisterPostBackControl on every postback
        • Response of link button inside update panel is too late in asp.net C#
        • Adjust Width of Button to match another, autosized one
        • ASP.NET update panel nested refreshing
        • how to change a css class of div in master page from update panel in content page
        • Why the Gridview backgroundcolor property not retaining on clicking link button in template field
        • Full postback triggered by CheckBox inside GridView inside UpdatePanel
        • Multiple web controls to trigger one Update Panel
        • Dropzone JS not working after update panel postback
        • Is there a way to force page position on a website that has an update panel that refreshes every 15 seconds?

        Related Questions in ASP.NET-MVC-VALIDATION

        • MVC disabling client side validation on a model field
        • MVC Core Validation - render as valid initially
        • c# mvc how to validate 3rd column Value Based on Two column
        • Jquery email validation is not working in MVC
        • ASP.NET MVC Html Helper: Adding a validation in an enum ddl
        • mvc validationMessage is not working while its in IEnumerable<T>
        • Model object is not validated if a member is invalid
        • ASP.NET MVC validation message does not display error message
        • Required field validator for a textbox in MVC depend on a dynamically generated drop down list
        • Cross-site scripting (XSS) patterns can be submitted
        • Radio button validation before post
        • ModelState.AddModelError - How can I makeup the Resource error string
        • How to validate input text for integers and decimals only?
        • How to manually add MVC client-side validation?
        • Regex to prevent the entering of white space?

        Related Questions in ASP.NET-MVC-AJAX

        • MVC Ajax form javascript not fired with InsertionMode = InsertionMode.InsertAfter
        • How to recieve and display JSON erroneous response in case of asp.net mvc Ajax in MVC 3.0 App
        • MVC filter action redirect to infinite loop
        • asp.net mvc ajax post - redirecttoaction not working
        • mvc2 with ajax table enabling back button
        • using ajax with dropdownlist mvc3
        • Javascript function to open a file not getting called
        • Is there a good explanation on what ASP.NET MVC3 is doing with its ajax helpers and rendering unobtrusive javascript?
        • Passing multiple ajax parameters to mvc controller
        • Can a partial view be used to do Ajax item updates?
        • Updating div content after submiting ajax form in asp.net MVC3
        • How to block targetUpdateId using Blockui using ajax.actionLink or ajax.beginForm
        • Ajax.RouteLink gives a 404
        • Ajax OnFailure function
        • The required anti-forgery form field __RequestVerificationToken is not present

        Popular Questions

        • How do I undo the most recent local commits in Git?
        • How can I remove a specific item from an array in JavaScript?
        • How do I delete a Git branch locally and remotely?
        • Find all files containing a specific text (string) on Linux?
        • How do I revert a Git repository to a previous commit?
        • How do I create an HTML button that acts like a link?
        • How do I check out a remote Git branch?
        • How do I force "git pull" to overwrite local files?
        • How do I list all files of a directory?
        • How to check whether a string contains a substring in JavaScript?
        • How do I redirect to another webpage?
        • How can I iterate over rows in a Pandas DataFrame?
        • How do I convert a String to an int in Java?
        • Does Python have a string 'contains' substring method?
        • How do I check if a string contains a specific word?

        Popular Tags

        javascript python java c# php android html jquery c++ css ios sql mysql r reactjs node.js arrays c asp.net json

        Trending Questions

        • UIImageView Frame Doesn't Reflect Constraints
        • Is it possible to use adb commands to click on a view by finding its ID?
        • How to create a new web character symbol recognizable by html/javascript?
        • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
        • Heap Gives Page Fault
        • Connect ffmpeg to Visual Studio 2008
        • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
        • How to avoid default initialization of objects in std::vector?
        • second argument of the command line arguments in a format other than char** argv or char* argv[]
        • How to improve efficiency of algorithm which generates next lexicographic permutation?
        • Navigating to the another actvity app getting crash in android
        • How to read the particular message format in android and store in sqlite database?
        • Resetting inventory status after order is cancelled
        • Efficiently compute powers of X in SSE/AVX
        • Insert into an external database using ajax and php : POST 500 (Internal Server Error)
        • Privacy
        • Terms
        • Cookies
        • Homegardensmart
        • Math
        • Aftereffectstemplates