Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. Show all posts

Thursday, September 13, 2012

Modal Dialog form view using JQuery ASP.Net MVC

Modal dialog form view using JQuery:

Create a project in VWD.


for convinence sake we will call it Modal_JQuery_ASPdotNet_MVC. You can name your project to you liking.

Now click Ok button. Select Internet Project and click Ok. The view engine I use is Razor, so I have selected Razor as my view engine.


Now the basic set up is done. We will have the following items created in Solution explorer for us to use.


Now as you can see you already have Home controller and Views for Home created. Since the modal doesn't have to do much with controller and view (apart from handling the logic and showing the view) we will work on Home controller and Home View to show our Modal dialog.

The idea of this sample is to show a partial view as modal dialog. So we also need to create a partial view which will be displayed as modal dialog. Right click on ~/views/shared/ folder and add a partial view.  As given below:



Now write the code for what you want displayed in the modal dialog. Say we are working on making a Contact Us form. So let's add code for the same.

<label for="Name">Name:</label ><br />

<input id="Namecontact" name="Name" type="text" /><br />

<label for="email">Email:</label><br />

<input id="emailcontact" name="email" type="text" /><br />

<label for="message">Message:</label><br />

<textarea id="messagecontact" name="message"></textarea>

<input class="close" name="submit" type="submit" value="Submit" />


code for the modal is complete with this partial implementation. Now all that remains is writing JQuery involved in respresenting this partial as modal dialog.
Now to start with the JQuery code. Open Index view in ~/Views/Home/. This view is already created by VWD when we created the project. Now for simplicity sake please delete all the below selected code in Index.cshtml.



Now start with the Jquery first include JQuery library, JQuery UI and JQuery Unobtrusive ajax extensions to your code. You can do that by adding the following code:

<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript">
</script>



Now moving forward we will create a action link on click of which will open the modal dialog.


@Html.ActionLink("Contact US","ContactUs","Home",null,
new {@class="openDialog",data_dialog_id="emailDialog",data_dialog_title="contactus"})



Let's break that down for you. @Html.Action generates anchor tag in HTML for us. It has many overload out of which the one we are using has the following component

@Html.ActionLink("Text of the link","Action to be called", "Controller in which action is present", "route values", "Html attributes to be assigned to anchor tag")
So here we have said create a anchor tag with text Contact US which will call the action name ContactUs in controller Home. It doesn't have any route values that is to say we are not passing any parameter to the action and its Html attributes are as follows:
it's class name is openDialog
it's data_dialog_id attribute is emailDialog
it's data_dialog_title attribute is contactus

so now below given HTML will be generated when you do view source:


<a class="openDialog" data-dialog-id="emailDialog" data-dialog-title="contactus" href="/Home/ContactUs">Contact US</a>


Note: data_dialog_id in @Html.ActionLink is converted to data-dialog-id when anchor tag is created. This happens automatically.
Also add a div to display the result thrown from the dailog to be displayed:


<div id="result"></div>


Now write JQuery to create the modal. (please remove comment in case this doesn't work, the comments are added for understanding and don't play any role in code.)


<script type="text/javascript">
    //Below code will clear cache
    $.ajaxSetup({ cache: false }); 
    //Below code will run the JQuery when document is ready. 
    $(document).ready(function () {
    //Below code will append a click event to the class openDialog 
    //which we assigned to the anchor previously
        $(".openDialog").live("click", function (e) {
            //Below code will prevent default action from occuring
            //when openDialog anchor is clicked
            e.preventDefault();
            //This is the actual implementation of the dailog
            $("<div></div>")
            //To the div created for dialog we will add class named dialog
            //this is done so that we can refer to the dialog later
            //we will see this in a short while why it is important
            .addClass("dialog")
            //add attribute add id attribute
            //note id attribute is assigned the same value as data-dialog-id
            //attribute in openDialog anchor
            .attr("id",$(this).attr("data-dialog-id"))
            //below code appends this div to body
            .appendTo("body")
            //below code describes the attribute for the dialog
            .dialog({
                //below code assigns title to the dialog
                //here we use same title as data-dialog-title attribute
                //in openDialog anchor tag
                title: $(this).attr("data-dialog-title"),
                //this will append code to close the dialog
                //and also put close cross(x) in dialog
                //we press ESC key in keyboard will also close dialog
                close: function () { $(this).remove() },
                //below code defines that the dialog is modal dialog
                modal:true
            })
            //below code says take href from openDialog anchor
            //which is /Home/ContactUs and load it to the modal dialog
            .load(this.href);
        });
    });
</script>


Now a small controller code needs to be written to open the modal dialog.
In Home controller write the following code:

public ActionResult ContactUs()
{    
   return PartialView("ContactUs");
}

Now, since we are refering the JQuery library in our Index file we need to clear JQuery reference from our _Layout.cshtml file. so in _Layout.cshtml find the line which says @Scripts.Render
("~/bundles/jquery") and comment it. The way to comment using razor syntax is as follows:


@*@Scripts.Render("~/bundles/jquery")*@
Note:Applies only to guys using VWD2012

Now for final touch so that your modal looks good include JQuery UI CSS in the _Layout.cshtml.


<link rel="stylesheet" type="text/css" href="../../Content/jquery-ui.css" />

And for simplicity sake I suggest you to remove the default style sheet's section which defines ui-dialog for ajax login because it conflicts with the JQuery UI CSS.
Note: Applies only to guys using VWD 2012.

Now our dialog can be opened and if we press ESC key the dialog will close.(screenshot below).


Note you can see that the partial ContactUs.cshtml which we created previously is reflected as dialog here. We can have any kind of form shown as dialog in this way.

Now what happens if I want to take the dialog's data after submit is clicked and process the data and also show it in the page as updated.

We will do that now.

Before we move on with the JQuery let's first create a ContactUs post method controller where we will do the logic processing.  The controller will look like this.


HttpPost]
public ActionResult ContactUs(string name,string email,string message)
{    /*Your other processing logic will go here*/
   return Json(new
   {
       nameret=name,
       emailret=email,
       messageret=message
     },JsonRequestBehavior.AllowGet);
}

Let me explain that to you. This controller will take name, email and message from the modal dialog as input and will output a Json result with name, email and message. Here before returning the content you can also save it to database you if want or you can write any other processing logic like you might want to append Mr/Mrs before the name.

After the controller is done now let's write JQuery code that will call this controller. We need to append this code in the previous script we had defined inside the $(document).ready() function.


//if you see that code in the partial view our submit button
//is defined as .close class, so below code says on document ready
//append click event to this button
$(".close").live("click", function (e) {
            //prevent default action on the button click
            e.preventDefault();
            //get value of name textbox id=Namecontact
            //put in variable name
            var name = $("#Namecontact").val();
            //get value of email textbox id=emailcontact
            //put in variable email
            var email = $("#emailcontact").val();
            //get value of message textarea id=messagecontact
            //put it in variable message
            //note since messagecontact is a textarea
            //we need to use .text() rather than .val()
            var message = $("#messagecontact").text();
            //Start ajax call
            $.ajax({
            //define method for sending data to controller
                type: "POST",
                //define controller URL
                url: "/Home/ContactUs",
                //define data to send to controller
                //if you remember our controller accepts
                //3 parameters name, email and message
                data: { "name": name, "email": email, "message": message },
                //create a success function
                //this method is executed if controller
                //defined by the URL is found
                //and it accepts the data sent
                //control comes to this point if the controller
                //is executed. So data in function(data)
                //contains the Json data we sent
                //from the controller
                success: function (data) {
                    //Now in the div with id result defined in
                    //index page previously we will put in the
                    //data. As you can see Json data is very 
                    //easy way of returning to ajax call because
                    //now you can simply say data(dot)variable sent
                   //and you will get the returned value.
                    $("#result").html("<ul><li>Name: " + data.nameret + "</li><li>Email: " + data.emailret+ "</li><li>Message: "+data.messageret+"</li></ul>");
                    //now close the modal dialog we opened
                    $(".dialog").dialog("close");
                },
                //control comes to this function if ajax doesn't
               //find the controller or controller doesn't accepts
               //the data sent or controller throws exception

                error: function (data) {
                    //If it happens alert user of the error
                    alert("There was error processing this");
                    //close the modal dialog
                    $(this).closest(".dialog").dialog("close");
                }
            });

        });

So this now completes our dialog. Please note that this JQuery needs to be inside $(document).ready() function.

PS: You can also add validations to this the modal form but I have not included it here. You can also send modal from dB to the Views and update those modal from result from the view. For this you will have to make changes to the controller actions defined.





Friday, May 4, 2012

Create Websites using SQL Express with ASP.NET MVC


I was trying my hand on learning ASP.NET MVC but one thing that create most problem for me was that most of the tutorials used SQL Compact (here after reffered as SQL CE). But I wanted to use SQL Express as my database server. I had to struggle a lot to find a way to make website using SQL Express and ASP.NET MVC. So I thought if I put it here it might help :)

To start with this, we first need to create a solution in VWD 2010 with MVC.

1. Create a project, choose a name for the project,  for convenience I have named it "MvcTest". Click "Ok" button.






2. Choose Internet Application and Razor as your view engine and click "Ok".



3. You will see that VWD creates different files for you automatically.



4. Now in the Model folder create a Model. You can name it Test.cs



5. In the class that is created add the columns you want to specify in the table in the database, for example here I have created “{get; set;}” property for four items, ID, Name, RollNumber and Fee. When database will be created by Entity framework of ASP.NET MVC these will represent the columns in the table that is created. The definition for table however is not included in this picture (below), that will be given in further steps.



6. Now create a context class. Name the same as TestContext. This context class will basically define the database and table for your application. For adding context class you need to refer to System.Data.Entity. After adding the context your class will basically look like below, here Tests represents your database and Test (given in DbSet<Test>) represents your table.



7. Now coming to the point where you add connection string to the webconfig file.

The connection string to use SQL CE is:

<add connectionstring="Data Source=|DataDirectory|Test.sdf" name="TestContext" providername="System.Data.SqlServerCe.4.0"/>

Courtesy : http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

We add this connection string to web.config file on the root of the solution.

To change the connection string to use SQLExpress we can use the following string:

<add name="TestContext" connectionString="Server=.\SQLExpress;Database=Test;Integrated Security=SSPI;User Instance=true" providerName="System.Data.SqlClient" />


Courtesy : Lot of google searches and some personal tweaks

Now once the connection string is defined in web.config file, we need to build the solution before we proceed.


8. Once you have built the solution in the controller folder try to add Test controller with the following parameters
a. Template: Controller with read/write actions and views, using Entity Framework
b. Model class: Test(MvcTest.Models)
c. Data context class: TestContext(MvcTest.Models)
d. Views: Razor (CSHTML)



9. Sometimes you will get an error saying “Unable to create dbo.Test”, if this happens I suggest adding Tests.mdf database manually to App_Data folder, you can do that by right clicking on the App_Data folder Add=>New Item=> SQL Server Database as given below:



10. Click on the add button. Now you will see magic happen. VWD will automatically create Index.cshtml, Details.cshtml, Create.cshtml, Edit.cshtml, Delete.cshtml files for you in your view directory.



11. Now you are free to use and tweak the application to your liking. As of now with this much code only you already have working application. Screen Shots for Index page, Create page, Edit page and Delete page is given below. To get to the Index page run the application from VWD using Ctrl+F5. In the address bar of Internet Explorer append “Test” to the address. eg. http://localhost:xxxx/Test

a. Index



b. Create (Click on Create New Hyperlink to get to this page)


c. Changed Index page. Once the data is created you are redirected back to Index.



d. Click on Edit, Details and Delete for viewing respective pages.

Hope this post helps you to use SQLExpress with ASP.NET MVC :)

PS: I have just started learning ASP.NET MVC, so I might have made some mistakes (which doesn’t look likely because the application is working but still) please help me to correct them.

Disclaimer: I am not the creator of ASP.NET, MVC, Razor or Entity, all I am trying to do is put up a simple tutorial in place using SQL Express and ASP.NET MVC and all my learning is from the resources collected from the internet.