Announcement

How to create a pop up window

Create a pop up window

create a pop up window using jquery in mvc4 techiners.in
Sometimes in our application we need to take input dynamically from the user such as when a user tries to submit a form which contains a drop down for selecting a Country that is mandatory, but the Country is not present in the drop down list which the user wants to select. If this is the case, than probably user will select any country in order to get rid of the error message of selecting mandatory country. There must be a way to dynamically add new country. So, In this post we will learn how to create a pop up window using jquery that will allow the user to add new country simultaneously loading it into drop down and make available for selection.

So, let us begin our step-by-step procedure to add a pop-up so that the user need
not go to another page for adding new country that will result into loosing all his information that user has filled in the current form and then returning back to the form, unnecessary creating a redirect.

Step 1 :We need to create a controller say Country, that has an ActionResult method Index that will return a View. Rename it to Create.

Step 2 :Right click on the Action method and select Create View and click on Add. This will create a view with the name Create. Inside the view write the following code for adding a label as Country, a search box to search the country and a drop down list for selecting the country. A link is provided as New clicking it will open a pop up window that will ask for Country Name to enter and submit the same.


<table>
<tr>
<td>
Country
: @Html.TextBox("CountrySearch", null, new { @id = "CountrySearch", @class = "TextBox", @onblur = "checkNumberOfChar('CountrySearch','ddlCountry')" })
</td>
<td>
@Html.DropDownList("CountryName", new List<SelectListItem> { }, new { @id = "ddlCountry" })
@Html.ActionLink("New", null, null, new { id = "open-country-popup", @class = "actionLink" })
</td>
</tr>
</table>

Step 3 :Notice that we have provided an id to CountrySearch text box, to drop down list as ddlCountry and to New link as open-country-popup. On onblur event of CountrySearch text box, we have called a JavaScript function checkNumberOfChar() and to it passed two parameters which are ids of Search box and drop down. Within this function we will check whether the user has entered minimum three characters or not, if not, than display an alert message to the user to enter at least three characters. If the characters are three or more than three, than it will call a method present in the controller using AJAX and the method will return JSON result consisting of all countries that will contain the characters typed in the search box.


Step 4 : Here is the complete code for the above method. The code should be placed in the View under script tag.


function checkNumberOfChar(search, control) {
if ($('#' + search).val().length > 0 && $('#' + search).val().length < 3){                 alert("Enter Minimum three characters.");

$("#" + control).empty();
}
else if ($('#' + search).val().length >= 3){
$.ajax({
url: '@Url.Action("GetData", "Visitor")',
data: { query: $('#' + search).val(), ctrlName: control },
dataType: 'json',
type: 'GET',
async: false,
success: function (result) {
$("#" + control).empty();
for (var j = 0; j < result.length; j++)

{
$("#" + control).append("<option                                                           value=" + result[j].Id + ">" +                                                             result[j].Name + "</option>");
}
}
})
}

Step 5 :Code for the partial view: _AddNewCountry.cshtml is (that will act as pop up):


@model Project.Entities.Country
<fieldset style="overflow: hidden; float: left; background-color: #eee;">
<legend>Create Country</legend>
<table>
<tr>
<td>
@Html.Label("Country Name")
</td>
<td>
@Html.TextBoxFor(model => model.CountryName)
@Html.ValidationMessageFor(model => model.CountryName)
</td>
</tr>
<tr>
<td align="center">
<input type="submit" value="Create" class="Button" id="btnCreateCountry" />
</td>
</tr>
</table>
</fieldset>

Step 6 :Here is the DIV with an id as dialog-model-country that should be in the view.

<div id="dialog-model-country" style="display: none;" title="Add New Country">
@Html.Partial("~/Views/Visitor/_AddNewCountry.cshtml")
</div>


Step 7 :Now, the code for opening pop up should be placed in the View under script tag is here:


$("#open-country-popup").live("click", function () {
$("#dialog-model-country").css("visibility", "visible");
/* resetTextField(id) is a function that will clear the text box. */
resetTextField("#CountryName");
$("#dialog-model-country").dialog({
width: 500,
height: 350,
resizeable: false,
title: "Add New Country",
buttons: {
Close: function () {
$(this).dialog('close');
}
},
/* modal is set to true so that it is a modal dialog box, wherein a user is not allowed to interact with the page when pop up is opened. Set it to false, if you want the user to interact with the page while pop up is opened. */
modal: true
});
return false;
});


Here is the code for resetTextField(id) function.

function resetTextField(id) {
$('div ' + id).val('');
};

Step 8 :Now, the main thing is code for pop up. This we need to handle on the click of New Action Link. So, with the help of Id of the New Action Link, we will open a jQuery dialog box. For this, we created a <div> in Step 6 that contains the code for rendering partial view. The div is provided an id as 'dialog-model-country'. It is the partial view created in Step 5 that actually contains the code for adding new country. The Partial View contains a label as Country Name, a text box for entering company name and a submit button as Create for creating the country. It is provided an id as btnCreateCountry on click of which we will fetch the country name entered in the text box by the user. Than using AJAX we will submit this country name to the controller CreateCountry JsonResult. This method will create an object of Country table, and then check for duplicate country name using LINQ or ADO.NET, if duplicates does not exists, than it will create an entry for the new country name and return a string as "2". If duplicate exists, than return a string as "1". Within javascript click event function of btnCreateCountry in the success method of AJAX we will check the result. If result is "1", than alert is displayed as 'This country is already added.' and close the dialog box. If result is "2", than alert is displayed as 'This country is added successfully.' and close the dialog box. The complete code for this event function is provided in next step.


Step 9 :Here is the complete code for the above explanation. The code should be placed in the View under script tag.


$("#btnCreateCountry").click(function () {
var CountryName = $('#CountryName').val();
if (CountryName != null && CountryName != "") {
var options = {};
/* Here is the call to the CreateCountry method of Country Controller */
options.url = '@Url.Action("CreateCountry","Country")';
options.type = "POST";
/* countryName as an argument */
options.data = JSON.stringify({ countryName: $("#CountryName").val() });
options.dataType = "json";
options.async = false;
options.contentType = "application/json";
options.success = function (count) {
if (count == 1) {
alert("This country is already added.");
$("#dialog-model-country").dialog('close');
}
else {
alert("This country is added successfully!!!");
LoadCountry();
$("#dialog-model-country").dialog('close');
}
}
/* In case there is any error in ajax than display an alert message. */
options.error = function () { alert("Error while adding country!"); };
$.ajax(options);
}
else {
alert("Country Name must not be left blank. Please enter Country Name.");
}
});

Step 10 : Code for the CreateCountry method:


public JsonResult CreateCountry(string countryName)
{
Country newCountry = new Country();
long duplicates = db.Country.Where(p => p.CountryName == countryName).Select(c => c.CountryId).FirstOrDefault();
var query = string.Empty;
if (duplicates > 0)
{
query = "1";
return Json(query, JsonRequestBehavior.AllowGet);
}
else
{
newCountry.CountryName = countryName;
bizCountry.Create(newCountry);
query = "2";
return Json(query, JsonRequestBehavior.AllowGet);
}
}

The Create method above uses the same method of ExecuteSP that is discussed in earlier post.


Step 11 : That's it. We are done. But, don't forget to add a reference to the appropriate jquery library.

CONCLUSION

So, we have seen how to create a pop up window using jQuery. Besides this, we also have seen how to create modal and modal less pop up just by setting modal:true or false respectively.

FEEDBACK

Hope the post will be useful for you in your programming career. What I need from you is to comment below and share with me your doubts and/or suggestions. Thank you :) Have a wonderful programming.

No comments: