a developer's notes – a semi-technical web development BLOG

March 21, 2014

Using jquery.validate.unobtrusive with jquery.maskedinput

Use a regular expression validator with your view model property. This regex will match “(999) 999-9999” and anything after. The input will be restricted with jquery.maskedinput to only accept valid numbers. Whether the user enters an extension or not, the regex will still get validated. We only need to valid the minimum required phone number.

Using the Data Annotation on your view model will allow the client side unobtrusive validation to work when the user enters in a phone number with the optional extension.

View Model property

[Required]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^([(][0-9]{3}[)][ ][0-9]{3}[-][0-9]{4})(.*)$", ErrorMessage = "Phone number busted.")]
[DisplayName("Contact Phone Number")]
public string ContactPhoneNumber { get; set; }

In your view

<div>
	@Html.EditorFor(x => x.ContactPhoneNumber)
	@Html.ValidationMessageFor(x => x.ContactPhoneNumber)
</div>

Script:

if ($("input[type=tel").length > 0) {
	$("input[type=tel").mask("(999) 999-9999? ext.9999", { placeholder: " " });

	// @Html.EditorFor is used to render any inputs that need the html 5 type attributes.
	// But @Html.EditorFor, won't allow you to add a css class, so we do it here.
	$('input[type=text],input[type=tel],input[type=datetime],input[type=date],input[type=number],input[type=password],textarea,input[type=email],input[type=url],input[type=zip]').each(function (idx, item) {
		if (!$(item).hasClass('form-control')) //class only for Bootstrap styling
			$(item).addClass('form-control');
	});

}
Advertisements

January 29, 2014

Dynamically added checkbox not posting value to Action Method in controller

I noticed that @Html.CheckboxFor(model => model.MyCheckBox) creates a hidden input with the same name as the actual checkbox. So when you dynamically add a checkbox, make sure you also add in a hidden input with the same name attribute.


var chkboxDiv = $(document.createElement('div')).attr({
	id: 'dynamicChkBoxdiv_'
});

chkboxDiv.html(
	'<input ' +
		'class="myChkBx"' +
		'type="checkbox"' +
		'value=""' +
		'data-val-required="The Active field is required."' +
		'data-val="true"' +
		'name="myChkBxName"/>' +
	'<input ' +
		'type="hidden"' +
		'value=""' +
		'name="myChkBxName"/>' +
);

You also need to add a click event handler to update the hidden value so when the form is submitted, the controller will get the correct ‘checked’ value.

Notice the second parameter that specifies a css class. When you add your dynamic controls, add a css class so you can specify which elements should get the click event delegate. All of your dynamically added controls that have the css class, will now have the same click event.

$("#dynamicChkBoxdiv_").parent().on("click", '.myChkBx', function (e) {
	var name = e.target.name;
	var checkVal = e.target.checked;
	$("input[name^='" + name + "']").val(checkVal); //this will update both the checkbox and hidden input's value
});

January 22, 2014

JQuery doesn’t work with ASP.NET MVC 4 Application. $ is not defined

Filed under: ASP.NET MVC — Duy Nguyen @ 11:29 am
Tags: , , , , , , , ,

Why is JQuery Referenced In the Body Tag with a default ASP.NET MVC 4 Application?

In short, script loading and executing, blocks the rendering of a web page. So it is recommended to move script references in the body tag. So Microsoft decided to move the @Scripts.Render in the body tag as the default location for _Layout.cshtml. If you’re using jquery’s onReady() function in your View, make sure you declare your script tag within a scripts @section like this:

@section Scripts {
    <script type="text/javascript">

    $(function () { //Same as $(document).ready()
        alert("hello");
    });
       
    </script>
}

If you declare a traditional <script> tag outside of “@section Script{}” at either at the beginning or end of your View file, you will get an error, $ is not defined. This is because the _layout view calls @RenderBody() before the jquery script bundle.

But if you still want to declare your <script>tags and not use @section Script{}, for whatever reason, remember to comment out or delete the

@Scripts.Render("~/bundles/jquery")

reference in the body tag in the _Layout.cshtml file and move it to the head tag.

Here is a sample _Layout.cshtml.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery") @*--Need to move this to the <head> section otherwise you will get '$ is undefined.'*@
</head>
<body>
    @RenderBody()

    @*-- Commenting out the default location because we are not using @section Scripts {} section. By default, Microsoft added all script rendering in the <body> tag for better performance. But this will only work if you define your script tags within @section Scripts {}.*@
    @*@Scripts.Render("~/bundles/jquery")*@ 
    @RenderSection("scripts", required: false)
</body>
</html>

December 4, 2013

WebClient .DownloadString with Proxy Server

Filed under: ASP.NET,ASP.NET MVC,C# — Duy Nguyen @ 9:19 am
Tags: , , , , , , ,

Code to use the default proxy settings

IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
client = new WebClient { Proxy = defaultWebProxy };
string downloadString = client.DownloadString("www.google.com");

or

WebClient client = new WebClient();
WebProxy wp = new WebProxy(" proxy server url here");
client.Proxy = wp;
string str = client.DownloadString("http://www.google.com");

If you need to set an account use this

using (WebClient webClient = new WebClient())
{
	webClient.Encoding = encoding;
	NetworkCredential netcredit = new NetworkCredential("MyNetworkUserID", "MyNetworkPassword", "corp");
	webClient.Credentials = netcredit;
	webClient.Proxy = new System.Net.WebProxy()
	{
		Credentials = new System.Net.NetworkCredential("MyNetworkUserID", "MyNetworkPassword", "corp")
	};
	// webClient.Proxy = null;//if I don't give webClient.Proxy-it returns Error "407-ProxyAuthentication Required!"
	result = webClient.DownloadString(url);
	  // result = webClient.DownloadString("http://www.google.com/");//just to check with google itself,still the same error
}

August 27, 2013

ASP.NET MVC Html.DropDownList and Html.DropDownListFor Examples

Html.DropDownList (Webforms Snytax)

View Model:

public class ViewModel
{
	public List<SelectListItem> MyList { get; set; }
}

Controller:


public ActionResult Index()
{
	var model = new ViewModel();            
	GetMyList(model);
	ViewData.Model = model;
	return PartialView("Index");
}

private void GetMyList(ViewModel model)
{
	var cars = (from d in this.Repository.Cars
				 where d.Id == User.Id
				 select d).ToList();
				 
	var listItems = new List<SelectListItem>();
	listItems.Add(new SelectListItem { Text = "-Select Item-", Value = "-1", Selected = true });
	listItems.AddRange(from d in cars
					 select new SelectListItem
					 {
						 Text = d.Desc,
						 Value = d.ID.ToString(),
						 Selected = false
					 });
													 
													 
	model.MyList = listItems;
}

View:

<%= Html.DropDownList("itemsDdlName", Model.MyList , null, null})%>

Html.DropDownListFor (Razor)

View Model:

public class ViewModel
{
	public List<City> Cities { get; set; } 
    public int? CityId { get; set; }
    public List<City> Cities { get; set; }   
}

public class City
{
	public int CityId { get; set; }
	public string CityDescription { get; set; }
}

Controller:


public ActionResult Index()
{
    var model = new ViewModel();           
    GetCities(model);
    ViewData.Model = model;
    return PartialView("Index");
}

private void GetCities(ViewModel m)
{
	using (var db = new CityEntities())
	{
		m.Cities = db.Cities.ToList();
	}
}

View:

@Html.DropDownListFor(model => model.CityId, Model.Cities.ToSelectListItems(x => x.CityDescription, x => x.CityId.ToString(), x => x.CityId == Model.CityId))

Create a free website or blog at WordPress.com.