European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

How to get textboxes values in MVC4 created by jQuery

clock October 30, 2013 11:22 by author Ronny

Yesterday, I was trying to get the values of TextBoxes created by jQuery. I was expecting to get the value of each Textbox created by jQuery by the Id attribute of the TextBox, but I was getting NULL. I tried to find out the reason behind this reason and finally I got the solution. Let's understand the ID and Name attribute of Html controls.
ID
Id attribute of an input html control is responsible for uniquely identified a control on the html page. We use Id for getting an input html control's value using jQuery at client side or for applying some CSS to that control.
Name
Name attribute of an input html control is responsible for posting that control values on server side.
Hence, while creating a Html TextBox or Dropdown list using jQuery also defined the Id and Name attributes of an Html TextBox or Dropdown list.
Note
When you will not defined the Name attributes of an Html TextBox or Dropdown list then form will not post the TextBox or Dropdown list values to the server. It means at controller's action result you will not find the Html TextBox or Dropdown list.
Suppose, you need to select no of customers from drop down list as shown below fig.

Also, Textboxes for entering customers full name are created by jQuery as shown below.

When you will submit the form you will get the Textboxes created by jQuery at controller side as shown below -

The View

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script>
$(document).ready(function () {
$("#ddl").change(function () {
var i = $("#ddl :selected").val();
var str = "";
for (var j = 1; j <= i; j++) {
var id = "txtCustomer" + j;
//Remember to add name attribute to get values at server side
str = str + "<span>Customer " + j + " Full Name: </span><input type='text' id='" + id + "' name='" + id + "'/><br/>";
}
$("#content").html(str);
});
});
</script>
<br />
@using (Html.BeginForm())
{
<h2>Get TextBoxes Values Created by jQuery</h2>
<span>Select No. of Customers </span>
<select name="ddl">
<option>Select</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<br />
<div>
</div>
<br />
<div align="center">
<input id="btnSave" value="Save" />
</div>
}

You can get the Html TextBox or Dropdown list values created by jQuery by two method as given below -

Method 1: Get Values Using FormCollection

public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form, string ddl)
{
for (int i = 1; i <= Convert.ToInt32(ddl); i++)
{
string id = "txtCustomer" + i;
string customer = form[id];
}
return View();
}

Method 2: Get Values Using Request.Form

public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string ddl)
{
for (int i = 1; i <= Convert.ToInt32(ddl); i++)
{
string id = "txtCustomer" + i;
string customer = Request.Form[id];
}
return View();
}

What do you think?
I hope you will enjoy the tips while programming with MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.



European ASP.NET MVC 4 Hosting - Amsterdam :: ValidateInput and AllowHtml attribute in MVC4

clock October 28, 2013 09:43 by author Scott

Sometimes, your required to save Html data in the database. By default Asp.Net MVC doesn't allow a user to submit html for avoiding Cross Site Scripting attack to your application. Suppose you have below form and you can submit the Html in description textarea.

If you do this and try to submit it you will get the error below

However, if you want to do this, you can achieve it by using ValidateInput attribute and AllowHtml attribute.

ValidateInput Attribute

This is the simple way to allow the submission of HTML. This attribute can enable or disable input validation at the controller level or at any action method.

ValidateInput at Controller Level

[ValidateInput(false)]
public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}

[HttpPost]
public ActionResult AddArticle(BlogModel blog)
{
if (ModelState.IsValid)
{

}
return View();
}
}

Now, the user can submit Html for this Controller successfully.

ValidateInput at Action Method Level

public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}

[ValidateInput(false)]
[HttpPost]
public ActionResult AddArticle(BlogModel blog)
{
if (ModelState.IsValid)
{

}
return View();
}
}

Now, the user can submit Html for this action method successfully.

Limitation of ValidateInput attribute

This attribute also has the issue since this allow the Html input for all the properties and that is unsafe. Since you have enable Html input for only one-two properties then how to do this. To allow Html input for a single property, you should useAllowHtml attribute.

AllowHtml Attribute

This is the best way to allow the submission of HTML for a particular property. This attribute will be added to the property of a model to bypass input validation for that property only. This explicit declaration is more secure than the ValidateInput attribute.

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc; 

public class BlogModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; } 

[AllowHtml]
[Required]
[Display(Name = "Description")]
public string Description{ get; set; } 

}

Make sure, you have removed the ValidateInput attribute from Conroller or Action method. Now, the user can submit Html only for the Description property successfully.



European ASP.NET MVC Hosting - Amsterdam :: Example Routing in ASP.NET MVC

clock October 18, 2013 12:32 by author Scott

Basically, Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event.

How to defining route...

    public static void RegisterRoutes(RouteCollection routes)
    {
    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // Route Pattern
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for above defined parameters
    );
    }    

    protected void Application_Start()
    {
    RegisterRoutes(RouteTable.Routes);
    //To:DO
    }

When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request to the appropriate controller and action. If there is no match in the route table for the incoming request's URL, it returns a 404 HTTP status code.

Note

Always remeber route name should be unique across the entire application. Route name cann't be duplicate.

How it works...

In above example we have defined the Route Pattern {controller}/{action}/{id} and also provide the default values for controller,action and id parameters. Default values means if you will not provide the values for controller or action or id defined in the pattern then these values will be serve by the routing system.

Suppose your webapplication is running on www.example.com then the url pattren for you application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system.

Difference between Routing and URL Rewriting

Many developers compares routing to URL rewritting that is wrong. Since both the approaches are very much different. Moreover, both the approaches can be used to make SEO friendly URLs. Below is the main difference between these two approaches.

  • URL rewriting is focused on mapping one URL (new url) to another URL (old url) while routing is focused on mapping a URL to a resource.
  • Actually, URL rewriting rewrites your old url to new one while routing never rewrite your old url to new one but it map to the original route.


Press Release - Premier European HostForLIFE.eu Proudly Announces FREE Trial Windows ASP.NET Hosting

clock October 8, 2013 12:33 by author Scott

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has officially launched FREE trial web hosting package. This free trial is offered for the next 14 days and at anytime, the customers can always cancel anytime. This FREE trial packages combine generous or unlimited web space, unlimited bandwith, unlimited email accounts, 1 MSSQL database, 1 MySQL database. There is also the ability to host multiple websites in this package. As the market for hosted solutions continues to grow, the new hosting range is designed to exceed the growing technical demands of businesses and IT professionals.

HostForLIFE.eu continues to invest heavily in developing powerful and resilient Business web hosting packages. The new range scales to accommodate a wide range of business needs including ecommerce and multiple websites. The range comprises of Classic Package, which is priced €3.00/month. The Budget Package is priced at €5.50/month. There is Economy package which is priced €8.00/month, this is the most favourite package and it is designed for Portal/Business site. And then Business Package is priced at €11.00/month. Furthermore, the Business Package delivers HostForLIFE’s most powerful shared hosting feature set to date, and is optimized for hosting multiple and business websites.

Every day thousands of people decide to set up a website for business or personal use. New business owners and the average consumer don't always have access to unlimited budgets. HostForLIFE.eu understand the importance of reliable hosting but are not always prepared to pay the exorbitant prices that reliable hosts charge.

“We believe that all customers should be given a free trial before buying into a service and with such approach, customers are confident that the product / service that they choose is not faulty or wrong.” Said John Curtis, VP Marketing and Business Development at HostForLIFE.eu. “With this free trial hosting, we want our customers to test drive our quality services. We believe that our web hosting platform and customer support are up there with the best and our commitment to give the best for our customers.”

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see www.microsoft.com/web/hosting/HostingProvider/Details/953). HostForLIFE.eu services is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, HostForLIFE.eu has also won several awards from reputable organizations in the hosting industry and the detail can be found on HostForLIFE.eu official website.

For more information about this FREE trial package offered by HostForLIFE.eu, please visit http://www.hostforlife.eu

About HostForLIFE.eu:

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu number one goal is constant uptime. HostForLIFE.eu data center uses cutting edge technology, processes, and equipment. HostForLIFE.eu has one of the best up time reputations in the industry.

HostForLIFE.eu second goal is providing excellent customer service. HostForLIFE.eu technical management structure is headed by professionals who have been in the industry since it's inception. HostForLIFE.eu has customers from around the globe, spread across every continent. HostForLIFE.eu serves the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.   



European ASP.NET MVC 4 Hosting - Amsterdam :: How To Build async Unit of Work with MVC 4

clock October 8, 2013 12:06 by author Ronny

In the RavenDB mailing list, How to combine the standard unit of work pattern of working with RavenDB in MVC applications with async. In particular, the problematic code was:

public class HomeController : Controller
   {
        public IAsyncDocumentSession Db { get; set; }
        public async Task<ActionResult> Index()
       {
            var person = new Person {Name = "Khalid Abuhakmeh"};
            await Db.StoreAsync(person);     

          return View(person);
       }
           protected override void OnActionExecuting(ActionExecutingContext filterContext)
       {
           Db = MvcApplication.DocumentStore.OpenAsyncSession();
           base.OnActionExecuting(filterContext);
       }

       protected override void OnActionExecuted(ActionExecutedContext filterContext)
       {
           Db.SaveChangesAsync()
               .ContinueWith(x => { });
           base.OnActionExecuted(filterContext);
       }
    lic class Person
       {
           public string Id { get; set; }
           public string Name { get; set; }
       }
   }

As you probably noticed, the problem Db.SaveChangesAsync(). We want to execute the save changes in an async manner, but we don’t want to do that in a way that would block the thread. The current code just assume the happy path, and any error would be ignored. That ain’t right. If we were using Web API, this would be trivially easy, but we aren’t. So let us see what can be done about it.

I created a new MVC 4 application and wrote the following code:

As you can see, I have a break point after the await, which means that when that break point is hit, I’ll be able to see what is responsible for handling async calls in MVC4. When the breakpoint was hit, I looked at the call stack, and saw:

 

Not very useful, right? But we can fix that:

And now we get:

This is a whole bunch of stuff that doesn’t really help, I am afraid. But then I thought about putting the breakpoint before the await, which gave me:

And this means that I can check the code here. I got the code and started digging. At first I thought that I couldn’t do it, but then I discovered that I could. See, all you have to do is to create you own async action invoker, like so:

 public class UnitOfWorkAsyncActionInvoker : AsyncControllerActionInvoker
   
{
  
     protected override IAsyncResult BeginInvokeActionMethod(
  
         ControllerContext controllerContext,
  
         ActionDescriptor actionDescriptor,
  
         IDictionary<string, object> parameters, AsyncCallback callback,
  
         object state)
  
    {
  
         return base.BeginInvokeActionMethod(controllerContext, actionDescriptor, parameters,
 
                                             result => DoSomethingAsyncAfterTask().ContinueWith(task => callback(task)),
 
                                             state);
 
     }
 
     public async Task DoSomethingAsyncAfterTask()
 
     {
 
         await Task.Delay(1000);
 
     }
  
}
And then register it :

   DependencyResolver.SetResolver(type =>
 
     {
 
         if (type == typeof (IAsyncActionInvoker))
 
             return new UnitOfWorkAsyncActionInvoker();
 
         return null;
 
     }, type => Enumerable.Empty<object>());

Note: Except for doing a minimum of F5 in the debugger, I have neither tested nor verified this code. It appears to do what I want it to, and since I am only getting to this because a customer asked about this in the mailing list, that is about as much investigation time that I can dedicate to it.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in