jQuery Ajax is simple to implement

The contact page and create blog are using ajax now.

Here's how I did it:
-Created Contact Model with Name, Email and Message -Created a controller with two actions Index for the initial view and send(note HttpPost annotation) as follows:

public ActionResult Index()
{
  Contact cc = new Contact();
  return View(cc);
}

[HttpPost]
public bool Send(Contact c)
{    
  if (ModelState.IsValid)
  {
   WebMail.SmtpServer = "smtp server";
   WebMail.UserName = "account Used To Send the email";
   WebMail.Password = "password";
   WebMail.Send("myAddress", "From-mvcdeveloper.net-UserName-" 
 + c.Name, c.Message, c.Email, "myCCAddress");
 return true;
}
else
throw new Exception("Invalid Email");
//return View(c);
}

-Created Index view page with HTML5 input types

-Here's the fun part. On the view page, I am posting the contents with matching parameters. MVC finds the matching model(Very cool stuff). It is called model binding and,routing as shown here takes care of it from there.

  • jQuery is as follows: $('#btnsend').click(function () {

        if ($("#sendForm").validate().form()) {
    
    
    
        var contact = {
            Name: $('#Name').val(),
            Email: $('#Email').val(),
            Message: $('#Message').val()
        };
    
    
        $.post('/Contact/Send', contact, function () {
    
    
            UserMessage("<h2>The message
    

    is sent. Thank you!");

            }).error(function () {
                UserMessage("<h2>The message sending failed. : (</h2>");
    
    
    
        });
    }
    else {
        return;
    }
    
    }); function UserMessage(msg) { $('#cSet').fadeOut(1000, "", function () { $('#success').delay(1000).fadeIn(1000, "", function () { $('#success').html(msg); }); }); }

One gotcha here is the bug in the version of jQuery validator plugin. Anything below 1.9.0 has a bug. It just doesnt validate the HTML5 input types properly. I spent a lot of time on this. I thought I was doing something wrong.

Try to use my contact page to see the demo.

Hope this helps! :)



comments powered by Disqus