Question

<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

Was it helpful?

Solution

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 :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top