22 Ağustos 2013 Perşembe

Asp Net Mvc Jqery Kullanımı

Mvc sayfa yenilemedn kaydetmek ve listelemek ( nesne kullanarak)

Controlu müzde olması gerekeneler:

  [HttpPost]
        public string FormdanAl(bilgiler b)
        {
            if (!String.IsNullOrEmpty(b.adi) && !String.IsNullOrEmpty(b.soyadi))
            {
                //TODO: Save the data in database
                bilgiler bdb = new bilgiler() { adi=b.adi, soyadi=b.soyadi,  kayittarihi = DateTime.Now, onay = true };
                db.bilgilers.Add(bdb);
                db.SaveChanges();
                return "Teşekkürler " +b.adi + ". Kayıt Alındı";
            }
            else
                return "Boş Alanları Doldurunuz.";
        }
        public JsonResult KisiListesi()
        {
            var result = from r in db.bilgilers.ToList()
                         select new { r.adi, r.soyadi };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

---------
Conroller bittikten sonra

-------------------------------
sayfamız sayfanın üstünede scriptimizin yolunu yazmalıyız scripti yazınca

<script src="~/Scripts/script.js"></script>


<div>  

    <form id="frm" action="/Home/FormdanAl" method="post">
<p>
    Enter your name
    <br />
    @Html.TextBox("Adi")
</p>
<p>
    Enter your address
    <br />
    @Html.TextBox("Soyadi")
</p>

<input type="button" value="Kaydet" id="Kaydet" />
        <span id="msg" style="color:red;"/>
</form>
</div>

<p>
    <input type="submit" id="KisiListesi" value="Getir"/>
    <input  type="submit" id="Gizle" value="Gizle" />
</p>
<p id="rData">
</p>

  ----------------------
sayfamızda bir form var bu form bilgileri yollayacak

---------------------------
scriptimiz de şu şekilde


$(document).ready(function () {

    $('#Kaydet').click(function () {

        var form = $("#frm");
        var url = form.attr("action");
        var formData = form.serialize();
        $.post(url, formData, function (data) {
            $("#msg").html(data);
            $('#KisiListesi').click();
        });
    });

    $('#KisiListesi').click(function () {
        $.getJSON('/Home/KisiListesi/', function (data) {
            $('#rData').show(500);
            $('#Gizle').show(800);
            $('#KisiListesi').hide(600);
            var items = '<table><tr><th>Adı</th><th>Soyadı</th></tr>';
            $.each(data, function (i, b) {
                items += "<tr><td>" + b.adi + "</td><td>" + b.soyadi + "</td></tr>";
            });
            items += "</table>";

            $('#rData').html(items);
        });
    });

    $('#Gizle').click(function () {
        $('#rData').hide(500);
        $('#Gizle').hide(800);
        $('#KisiListesi').show(600);
    });
});


bu kadar kolay gelsin. :)

21 Ağustos 2013 Çarşamba

Mvc validation Renkli div ile

Client Side Username Availability Checking in MVC

It is often required live ‘username’ checking on user registration page in web applications. Today I developed this for my one of the web application and would like to share that with you.

Let’s look at the gif screen before looking at the code.



Now, to develop this you just need make an Ajax GET call to a method sitting inside ‘Account’ controller.

Here is the Register.cshtml code, I highlighted the changed made.

@model MvcApplication1.Models.RegisterModel
@{
    ViewBag.Title = "Register";
}

<hgroup class="title">
    <h1>@ViewBag.Title.</h1>
    <h2>Create a new account.</h2>
</hgroup>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.UserName)
                @Html.TextBoxFor(m => m.UserName)
                <span id="result" />
            </li>
            <li>
                @Html.LabelFor(m => m.Password)
                @Html.PasswordFor(m => m.Password)
            </li>
            <li>
                @Html.LabelFor(m => m.ConfirmPassword)
                @Html.PasswordFor(m => m.ConfirmPassword)
            </li>
        </ol>
        <input type="submit" value="Register" />
    </fieldset>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/jscript">
        $('#UserName').blur(function () {
            var url = "/Account/CheckUserName";
            var name = $('#UserName').val();
            $.get(url, { input: name }, function (data) {
                if (data == "Available") {
                    $("#result").html("<span style='color:green'>Available</span>");
                    $("#UserName").css('background-color''');
                }
                else {
                    $("#result").html("<span style='color:red'>Not Available</span>");
                    $("#UserName").css('background-color''#e97878');
                }
            });
        })
    </script>
}

Now, look at the method sitting inside Account controller.

[AllowAnonymous]
public string CheckUserName(string input)
{
    bool ifuser = WebSecurity.UserExists(input);

    if (ifuser == false)
    {
        return "Available";
    }

    if (ifuser == true)
    {
        return "Not Available";
    }

    return "";
}

In case, if you wish to watch the video of this article?

jQuery Ajax mvc kullanımı detaylı

jQuery Ajax GET and POST calls to Controller's Method in MVC

In this blog post I am going to cover some really interesting stuff which is very useful today in web application developments. You will learn how to make jQuery Ajax GET and POST calls to controller methods.

When we use jQuery Ajax to access server (controller’s method) without reloading the web page we have two choices on how to pass the information for the request to the server (controller’s method). These two options are to use GET or POST.

Note: Before getting started with coding make sure, you are using jQuery library before the GET or POST script.

GET

GET is used to request data from a specified resource. With all the GET request we pass the url which is compulsory, however it can take following overloads.

.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail

Now, let’s try to use GET in MVC application.


GET call to Controller’s Method which will return string data

Let’s imagine we have following method in the controller.

public string TellMeDate()
{
    return DateTime.Today.ToString();
}

This method will return string data (date-time) when we call it, let’s make an async call using jQuery Ajax.

<p id="rData">
</p>

<script type="text/jscript">
    var url = "/Home/TellMeDate";
    $.get(url, nullfunction (data) {
        $("#rData").html(data);
    });
</script>

When page gets load, jQuery Ajax will generate an Ajax GET request/call. The first parameter is the URL and second is data (this is an optional, even we can avoid typing ‘null’) and third is success function when the response is received. The success function takes one parameter ‘data’ that holds the string content and we attached this content to a DOM element.

If you want to generate Ajax GET request when user clicks button, we can use following instead.

<script type="text/jscript">
    $('#ButtonID').click(function () {
        var url = "/Home/TellMeDate";
        $.get(url, nullfunction (data) {
            $("#rData").html(data);
        });
    })
</script>

If you run the application, you will see following output.



GET call with parameter to Controller’s Method which will return string data

Let’s imagine we have following method in the controller.

public string WelcomeMsg(string input)
{
    if (!String.IsNullOrEmpty(input))
        return "Please welcome " + input + ".";
    else
        return "Please enter your name.";
}

This method will accept a parameter and will return string data (welcome message or instruction message) when we call it. Now, let’s make an async call to this method using jQuery Ajax.

<p>
    Enter you name @Html.TextBox("Name")
    <input type="submit" id="SubmitName" value="Submit"/>
</p>

<script type="text/jscript">
    $('#SubmitName').click(function () {
        var url = "/Home/WelcomeMsg";
        var name = $('#Name').val();
        $.get(url, { input: name }, function (data) {
            $("#rData").html(data);
        });
    })
</script>

As you can see, when we click the button after typing name in textbox, jQuery Ajax will generate an Ajax GET request/call. Notice that the second parameter to the ‘get’ function now contains a key { input: name } (parameter). This example supplies one parameter, but can be extended to provide multiple parameters. The result of the above looks like the following:



GET call with parameter to Controller’s Method which will return JSON data

Controller’s method we have used above returned simple strings. Now, to deal with complex data we need JSON. The method given below will return JsonResult having ContactName and Address of customer’s from NorthwindEntities. I am using Northwind database and EF Database First approach in this sample.

public JsonResult CustomerList(string Id)
{
    NorthwindEntities db = new NorthwindEntities();
    var result = from r in db.Customers
                    where r.Country == Id
                    select new { r.ContactName, r.Address };
    return Json(result, JsonRequestBehavior.AllowGet);
}

Above method will accept Id as parameter and will return ‘JsonResult’. This action method can be called using the following jQuery Ajax GET call.


<p id="rData">
</p>

<p>
    Enter country name @Html.TextBox("Country")
    <input type="submit" id="GetCustomers" value="Submit"/>
</p>

<script type="text/jscript">
    $('#GetCustomers').click(function () {
        $.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {

            var items = '<table><tr><th>Name</th><th>Address</th></tr>';
            $.each(data, function (i, country) {
                items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";
            });
            items += "</table>";

            $('#rData').html(items);
        });
    })
</script>

As you can see, when we click the button after typing country name in textbox, jQuery Ajax will generate an Ajax GET request/call. Notice that the ‘getJSON’ function now contains URL in format ‘/Controller/ActionMethod/Key, here key (parameter) is supplied country name. The result of the above looks like the following:



Using Firebug we can sniff the response. A screen shot is shown below:


In above example we have used textbox where we typed country name and clicked on button to get the list of customers.

Alternatively, we can populate the list of country in dropdownlist box and then when user will select the country name from dropdownlist, we can display the list of customers.


Here is the controller that will populate the country list in dropdownlist box.

public ActionResult About()
{
    var result = from r in db.Customers
                    select r.Country;
    ViewBag.Country = result;

    return View();
}

Now, once we have list of country in dropdownlist box, we can implement Ajax GET request/call. Here it is with complete view page.

@Html.DropDownListFor(model => model.Country, new SelectList(ViewBag.Country), "Select Country")

<p id="rData">
</p>

@section Scripts {
    <script type="text/jscript">
        $('#Country').click(function () {
            $.getJSON('/Home/CustomerList/' + $('#Country').val(), function (data) {

                var items = '<table><tr><th>Name</th><th>Address</th></tr>';
                $.each(data, function (i, country) {
                    items += "<tr><td>" + country.ContactName + "</td><td>" + country.Address + "</td></tr>";
                });
                items += "</table>";

                $('#rData').html(items);
            });
        })
    </script>
}

Everything remains same like above textbox version.

POST

POST is used to submit data to be processed to a specified resource. With all the POST request we pass the url which is compulsory and data, however it can take following overloads. 

.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

Now, let’s try to use POST in MVC application.


POST call to Controller’s Method to save textbox data (not form)

There are various ways to POST form data to method but in the example given below I’m not going to use any form. I will just use two textboxes and a submit button, when user will click the button I want to save data via jQuery Ajax POST call. So, here is the method accepting two parameters name and address.

[HttpPost]
public string SubmitSubscription(string Name, string Address)
{
    if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Address))
        //TODO: Save the data in database
        return "Thank you " + Name + ". Record Saved.";
    else
        return "Please complete the form.";
           
}

We can implement above method to save data in database, it will also return the response back to client. Here is the jQuery Ajax POST function.

<h2>Subscription</h2>

<p>
    Enter your name
    <br />
    @Html.TextBox("Name")
</p>
<p>
    Enter your address
    <br />
    @Html.TextBox("Address")
</p>

<input type="button" value="Save" id="Save" />
<span id="msg" style="color:red;"/>

<script type="text/javascript">
    $('#Save').click(function () {
        var url = "/Home/SubmitSubscription";
        var name = $("#Name").val();
        var address = $("#Address").val();
        $.post(url, { Name: name, Address: address }, function (data) {
            $("#msg").html(data);
        });
    })
</script>

When you run above application it will look like following.



POST call to Controller’s Method to save form data

In above case we don’t have form, so I have used two individual properties/parameters (name, address) with jQuery Ajax POST call and also on method side, but this approach will be painful as number of properties increase. In this case we can use model approach that will allow us working with intelisense. So, let’s go and create ‘Subscription’ model class with two properties.

public class Subscription
{
    public string Name { getset; }
    public string Address { getset; }
}

Now, once we have model we can create our controller method.

[HttpPost]
public string SubmitSubscription(Subscription subs)
{
    if (!String.IsNullOrEmpty(subs.Name) && !String.IsNullOrEmpty(subs.Address))
        //TODO: Save the data in database
        return "Thank you " + subs.Name + ". Record Saved.";
    else
        return "Please complete the form.";
           
}

Still same just using model instead of individual properties.

<h2>Subscription</h2>

<form id="subscriptionForm" action="/Home/SubmitSubscription" method="post">
<p>
    Enter your name
    <br />
    @Html.TextBox("Name")
</p>
<p>
    Enter your address
    <br />
    @Html.TextBox("Address")
</p>

<input type="button" value="Save" id="Save" />
<span id="msg" style="color:red;"/>
</form>

@section Scripts{
    <script type="text/javascript">
        $('#Save').click(function () {

            var form = $("#subscriptionForm");
            var url = form.attr("action");
            var formData = form.serialize();
            $.post(url, formData, function (data) {
                $("#msg").html(data);
            });
        })
    </script>
}

Noting new, everything same just few changes allowed us to work with form.

Hope this helps.