@{ 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"/>
        DEVHIDE
        • Home (current)
        • About
        • Contact
        • Cookie
        • Home (current)
        • About
        • Contact
        • Cookie
        • Disclaimer
        • Privacy
        • TOS
        Login Or Sign up

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

        4.5k Views Asked by user At 03 August 2012 at 08:07 2025-11-26T03:59:47.123000
        <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 best solutions below

        5
        Shyju Shyju On 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

        • Can MVC.NET prevent SQL-injection at razor or controller level?
        • Getting and passing MVC Model data to AngularJS controller
        • Access property of an object of type [Model] in JQuery
        • Entity Framework Code First with Fluent API Concurrency `DbUpdateConcurrencyException` Not Raising
        • Bundling and minification issue in MVC
        • ASP-MVC Code-first migrations checkbox not active
        • Why does Azure CloudConfigurationManager.GetSetting return null
        • Dynamic roles list in CustomAuthorize ASP MVC
        • Jquery: Change contents of <select> tag dynamically
        • Why web API return 404 when deploy to IIS
        • MVC route URL not containing parameter
        • Invalidate user credentials when password changes
        • MVC : Insert data to two tables
        • MVC - Only allow users to edit their own data
        • Submit Button on Razor View doesn't call Action Result - MVC

        Related Questions in RAZOR

        • Getting and passing MVC Model data to AngularJS controller
        • Implement Onfailure in webApi controller
        • Dynamic roles list in CustomAuthorize ASP MVC
        • Jquery: Change contents of <select> tag dynamically
        • Submit Button on Razor View doesn't call Action Result - MVC
        • ASP MVC 5 Html.EditorFor not working / Unable to access/use Default Editor Templates
        • Convert string to date time in a `cshtml` file using razor?
        • jQuery: How to traverse / Iterate over a list of object
        • Switching CSS Just for that view?
        • Hyperlink in table header is not rendering
        • why Special characters apostrophe and others shows like this ’, in HTMl file
        • Display a tooltip with Html helper
        • Cannot access conditional Razor variable as href
        • MVC How to bundle html templates of type "text/html"?
        • Set a label value for a checkbox helper in asp.net mvc

        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

        • Change ASP.NET MVC validation dynamically in Jquery
        • mvc duplicate user validation error
        • Remote ViewModel validation of nested objects not working
        • asp.net Validation on DropDownList box
        • Localization of Required field validation message based on language selection from application in MVC
        • trying to inherit RegularExpressionAttribute, no longer validates
        • Data Validation in MVC
        • ModelState Validation In Multiple Add Scenario
        • MVC 5 model validation message not correctly displaying
        • How to add validation for a list in a ViewModel
        • InvalidOperationException was unhandled by user code
        • MVC 3 Validation - Format datetime
        • ASP.NET MVC - Validation Summary and BlockUI
        • Null values when using remote validation in MVC3
        • Client side validation not working for hidden field in asp.net mvc 3

        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

        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)

        Popular # Hahtags

        javascript python java c# php android html jquery c++ css ios sql mysql r reactjs

        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?
        .

        Copyright © 2021 Jogjafile Inc.

        • Disclaimer
        • Privacy
        • TOS
        • Homegardensmart
        • Math
        • Aftereffectstemplates