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

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Get Lookup Data in ASP.NET MVC 6?

clock April 12, 2019 12:28 by author Peter

In this article, I will explain about getting lookup dataa into you view ASP.Net MVC 6. This is a super common problem I encounter when building ASP.net MVC applications. I have a form that has a drop down box. Not only do I need to select the correct item from the edit model to pick from the drop down but I need to populate the drop down with the possible values.

Over the years I've used two approaches to doing this. The first is to push into the ViewBag a list of values in the controller action. That looks like
public ActionResult Edit(int id){ 
    var model = repository.get(id);

    ViewBag.Provinces = provincesService.List();

    return View(model);
}
Then in the view you can retrieve this data and use it to populate the drop down. If you're using the HTML helpers then this looks like

@Html.DropDownListFor(x=>x.province, (IEnumerable<SelectListItem>)ViewBag.Provinces)
This becomes somewhat messy when you have a lot of drop downs on a page. For instance consider something like

public ActionResult Edit(int id){ 
  var model = repository.get(id);

    ViewBag.Provinces = provincesService.List();
    ViewBag.States = statesService.List();
    ViewBag.StreetDirections = streetDirectionsService.List();
    ViewBag.Countries = countriesService.List();
    ViewBag.Counties = countiesService.List();

    return View(model);
}

The work of building up the data in the model becomes the primary focus of the view. We could extract it to a method but then we have to go hunting to find the different drop downs that are being populated. An approach I've taken in the past is to annotate the methods with an action filter to populate the ViewBag for me. This makes the action look like

[ProvincesFilter]
[StatesFilter]
[StreetDirectionsFilter]
[CountriesFilter]
[CountiesFilter]
public ActionResult Edit(int id){ 
  var model = repository.get(id);
  return View(model);
}

One of the filters might look like

public override void OnActionExecuting(ActionExecutingContext filterContext) 
{
    var countries = new List<SelectListItem>();
    if ((countries = (filterContext.HttpContext.Cache.Get(GetType().FullName) as List<SelectListItem>)) == null)
    {
        countries = countriesService.List();
        filterContext.HttpContext.Cache.Insert(GetType().FullName, countries);
    }
    filterContext.Controller.ViewBag.Countries = countries;
    base.OnActionExecuting(filterContext);
}

This filter also adds a degree of caching to the request so that we don't have to keep bugging the database.

Keeping a lot of data in the view bag presents a lot of opportunities for error. We don't have any sort of intellisense with the dynamic view object and I frequently use the wrong name in the controller and view, by mistake. Finally building the drop down box using the HTML helper requires some nasty looking casting. Any time I cast I feel uncomfortable.

@Html.DropDownListFor(x=>x.province, (IEnumerable<SelectListItem>)ViewBag.Provinces)
Now a lot of people prefer transferring the data as part of the model; this is the second approach. There is nothing special about this approach you just put some collections into the model.

I've always disliked this approach because it mixes the data needed for editing with the data for the drop downs which is really incidental. This data seems like a view level concern that really doesn't belong in the view model. This is a bit of a point of contention and I've challenged more than one person to a fight to the death over this very thing.

So neither option is particularly palatable. What we need is a third option and the new dependency injection capabilities of ASP.net MVC open up just such an option: we can inject the data services directly into the view. This means that we can consume the data right where we retrieve it without having to hammer it into some bloated DTO. We also don't have to worry about annotating our action or filling it with junk view specific code.

To start let's create a really simple service to return states.

public interface IStateService 
{
    IEnumerable<State> List();
}

public class StateService : IStateService 
{
    public IEnumerable<State> List() {
        return new List<State>
        {
            new State { Abbreviation = "AK", Name = "Alaska" },
            new State { Abbreviation = "AL", Name = "Alabama" }
        };
    }
}

Umm, looks like we're down to only two states, sorry Kentucky.

Now we can add this to our container. I took a singleton approach and just registered a single instance in the Startup.cs.

services.AddInstance(typeof(IStateService), new StateService()); 
This is easily added the the view by adding

@inject ViewInjection.Services.IStateService StateService

As the first line in the file. Then the final step is to actually make use of the service to populate a drop down box:

<div class="col-lg-12"> 
        @Html.DropDownList("States", StateService.List().Select(x => new SelectListItem { Text = x.Name, Value = x.Abbreviation }))
</div> 

That's it! Now we have a brand new way of getting the data we need to the view without having to clutter up our controller with anything that should be contained in the view.

HostForLIFE.eu ASP.NET MVC 6 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Easiest Way to Make CheckBox

clock March 29, 2019 11:53 by author Peter

In this article I show you, how easy it is to make a CheckBox on ASP.NET. The use of radio buttons and checkboxes using ASP.Net programming where the function of the radio button is choosing just one selection with a circle that is a point in the middle if we choose it. While the checkbox is square shaped that there is a tick if selected. To create a function of the radio button. We will explain below:

  • First you must create a project by choosing ASP.Net which is in the File> New Project> Other Languages> Visual C #> Web> Select Empty ASP.Net Web Application.
  • Fill in the name and click OK aspproject05
  • Right Click On aspproject05 in the top right corner select ADD> New Item> Web Form. And give CheckBox.aspx as a name.
  • Next create a CheckBox, button, label by entering this code is in the <div>

<asp:CheckBox ID="chkNews" Text="Do you want to get more update ?" runat="server" />
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" /> <hr/>
<asp:Label ID="lblResult" runat="server" />


Code Description:

<Asp: CheckBox ID = "chkNews" Text = "Do you want to get more update ?" runat = "server" />
This script serves as the manufacture CheckBox with ID named chkNews, which says Do you want to get more update? sent or received by the server.

<br />
This script is used to create a new line

<Asp: Button ID = "btnSubmit" Text = "Submit" runat = "server" OnClick = "btnSubmit_Click" />
This script is used to manufacture the ID button button named btnSubmit, that says Submit sent to the server to have an action Click if the button is clicked.

<Asp: Label ID = "lblResult" runat = "server" />

This script serves to create a label with name ID lblResult the printed blanks to be sent to the server.


When you're done simply double-Click button and type in the code below:

lblResult.Text = chkNews.Checked.ToString ();


Code Description:

LblResult.Text = chkNews.Checked.ToString ();

The above code serves as outputan of chkBerita when checked or not displayed by a label that berID lblResult that are boolean. This means that when we press the button without us tick checkbox section will appear on labels False lblResult whereas if we check the CheckBox and pressing the button it will show True.

HostForLIFE.eu ASP.NET MVC Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET MVC Request Life Cycle

clock March 12, 2019 09:39 by author Peter

If you have worked on ASP.NET MVC, you must be familiar with how when you type in an URL, the appropriate controller is chosen, and the action fired. Today we will dig a little deeper within the MVC request life cycle. Before we start discussing its life cycle, let's briefly understand the concept of HttpHandlers and HttpModules.

Handlers are responsible for generating the actual response in MVC. They implement the IHttpHandler class and only one handler will execute per request. On the other hand, HttpModules are created in response to life cycle events. Modules can, for example, be used for populating HttpContext objects. A request can use many modules. These classes derive from IHttpModule. We are now ready to learn about the MVC Request Life Cycle. The MVC life cycle can be briefly demonstrated as below,


When a request is fired for the first time, the Application_Start method in the Global.asax file is called. This method calls the RegisterRoutes method as below,
    public class MvcApplication : System.Web.HttpApplication 
        { 
            protected void Application_Start() 
            { 
                AreaRegistration.RegisterAllAreas(); 
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
                RouteConfig.RegisterRoutes(RouteTable.Routes); 
                BundleConfig.RegisterBundles(BundleTable.Bundles); 
            } 
        } 



RegisterRoutes method stores the routes defined in that method, in a static collection in the Routetable class.
Each route has an HttpHandler defined for it. In our case above, the MapRoute method defines the HttpHandler.
Next, the URLRoutingModule is called. It matches the request route with the routes defined in the route table. It calls the GetHttpHandler method which returns an instance of an MVCHandler.

The MVCHandler calls the ProcessRequest method. The controller execution and initialization happens inside this method. ProcessRequest calls ProcessRequestInit, which uses ControllerFactory to select an appropriate controller based on the supplied route. The ControllerFactory calls the Controller Activator which uses the dependency resolver to create an instance of the controller class.

Once the controller is created its Execute method is called.

Now comes the point where the action must be executed. The execute method in the controller calls the ExecuteCore method which calls the InvokeAction method of ActionInvoker. Action Invoker determines which action must be selected based on certain conditions, depending upon the methods available, their names and the action selectors used for them.

Once the action is selected, Authentication & Authorization filters are fired next.
Once the action passes through the authentication and authorization filter checks, the model binding takes place. The information needed for the action to execute is gathered in this step.

OnActionExecuting action filters are fired next. Once the OnActionExecuting filters are executed a response for the action is generated. The thing to note here is that the response is generated at this stage, but not executed.

Next, the OnActionExecuted filters are executed.  Once all the filters have finished executing, the response is finally executed in the ExecuteResult method which is called from the InvokeActionResult by the ActionInvoker. If the response is a view or a partial view, the ViewEngine will render it, else it will be handled appropriately. The ExecuteResult will find the appropriate view using FindView or FindPartialView method. This method will search for the view in specific locations and then render it. This is the final step in generating the response.

If you would like to further dig into the MVC request life cycle, I would highly recommend Alex Wolf’s pluralsight course by the same name.

HostForLIFE.eu ASP.NET MVC 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET MVC Hosting :: How to Integrate Your ASP.NET MVC with Paypal

clock March 5, 2019 08:27 by author Scott

PayPal is an online payment service that allows you to pay for purchases, receive payments, or to send and receive money. To receive these services, a person must submit various financial details to PayPal, such as credit card number, transmission can be done by mail. Thereafter, transactions are conducted without having to disclose financial details, an email address and a password is sufficient.

for more information about business please visit official Paypal Website for business or https://developer.paypal.com/webapps/developer/docs/integration/direct/log-in-with-paypal/detailed/

In this tutorial we propose to integrate the PAYPAL  e-commerce payment solution.

So, we are using Visual studio C# and ASP.NET MVC4 (for more information about ASP.NET MVC please take a look at  http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4

Ready ? Lets start our tutorial :

1. Open Visual studio 2012 or later and Create your Project

2.  Choose ASP.NET MVC4 Template Projet, Internet Application and Razor ViewEngine

 

3. Expand Model folder and Create a new Model named PayPalModel to hold PayPal payment parameters

Try it 

public class PayPalModel
{
public string cmd { get; set; }
public string business { get; set; }
public string no_shipping { get; set; }
public string @return { get; set; }
public string cancel_return { get; set; }
public string notify_url { get; set; }
public string currency_code { get; set; }
public string item_name { get; set; }
public string amount { get; set; }
public string actionURL { get; set; }

public PayPalModel(bool useSandbox)
{
this.cmd = “_xclick”;
this.business = ConfigurationManager.AppSettings[“business”];
this.cancel_return = ConfigurationManager.AppSettings[“cancel_return”];
this.@return = ConfigurationManager.AppSettings[“return”];
if (useSandbox)
{
this.actionURL = ConfigurationManager.AppSettings[“test_url”];
}
else
{
this.actionURL = ConfigurationManager.AppSettings[“Prod_url”];
}
// We can add parameters here, for example OrderId, CustomerId, etc….
this.notify_url = ConfigurationManager.AppSettings[“notify_url”];
// We can add parameters here, for example OrderId, CustomerId, etc….
this.currency_code = ConfigurationManager.AppSettings[“currency_code”];
}
}

4. Create a Paypal Controller

Try it :

public class PayPalController : Controller
{
public ActionResult RedirectFromPaypal()
{
return View();
}

public ActionResult CancelFromPaypal()
{
return View();
}

public ActionResult NotifyFromPaypal()
{
return View();
}

public ActionResult ValidateCommand(string product, string totalPrice)
{
return View();
}
}

5. Now Create a Partial View (ValidateCommand.csHtml)  to use our Model.  Do not forget that all fields must be of type hidden

try it :

@model PaypalMVC.Models.PayPalModel

<body>
<form id=”hiddenform” [email protected]>
@Html.HiddenFor(model => model.cmd)
@Html.HiddenFor(model => model.business)
@Html.HiddenFor(model => model.no_shipping)
@Html.HiddenFor(model => model.@return)
@Html.HiddenFor(model => model.cancel_return)
@Html.HiddenFor(model => model.notify_url)
@Html.HiddenFor(model => model.currency_code)
@Html.HiddenFor(model => model.item_name)
@Html.HiddenFor(model => model.amount)
</form>

<p style=”text-align: center”>
<h3>
Connecting to Paypal , please wait …

</h3>
</p>
</body>
@Scripts.Render(“~/bundles/jquery”)

<script type=”text/javascript” language=”javascript”>
$(this.document).ready(function () {
var form = $(“form”);
form.submit();
});
</script>

6. Now finish our ValidateCommand action of PayPalController

try it :

public ActionResult ValidateCommand(string product, string totalPrice)
{
bool useSandbox = Convert.ToBoolean(ConfigurationManager.AppSettings[“IsSandbox”]);
var paypal = new PayPalModel(useSandbox);

paypal.item_name = product;
paypal.amount = totalPrice;
return View(paypal);
}

7. Next finish our partialView by adding a jquery code to auto submit our form. The necessary scripts are  Jquery-{version}.js and    Jquery-{version}.min.js. Here we are used  @Scripts.Render(“~/bundles/jquery”)  to include all Jquery scripts.  A more better practice will be to export all javascript functions to external file but the submit function must be called just after displaying hidden field of our form

8. The next step is to create our checkOut form that dispays product name , Quantity, price and Total :

So expand View folder , expand Home folder and open index.csHtml file. Replace its contents by the following

try it : 

@{
ViewBag.Title = “Home Page”;
}
@using (Html.BeginForm(“ValidateCommand”, “PayPal”))
{
<div>
<table >
<tr>
<td>
product Name:
</td>
<td>
<input type=”text” name=”product” value=”Visual Studio 2013″ readonly />
</td>
</tr>
<tr>
<td>
Total Price:
</td>
<td>
$<input type=”text” name=”totalPrice” value=”14800″ readonly />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type=”submit” name=”btnConfirm” value=”Check Out with Paypal” />
</td>
</tr>
</table>
</div>
}

9. we are at the end. Our final step is to update the web.config file with the appropriate settings

10. Let’s test and run the application

 

11. Confirm payment by clicking on button Check Out With PayPal, then you will be redirected to the payment page 

We have this page error because, we have not yet an valid account.

Now it time to create a test account by following this link https://developer.paypal.com/webapps/developer/docs/classic/lifecycle/ug_sandbox/#accounts

12. Open Web.config file and update business value with your test account 

 

13. So run again your application. Confirm or Cancel , etc…

Hope this tutorial helps you. 

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Create A Password Protected PDF In MVC

clock February 19, 2019 10:37 by author Peter
Sometimes, we need to create a PDF file that opens only when the users put in a password when prompted. Let us see how to create a password-protected PDF file in MVC.

First, let's open Visual Studio and create a new project. We need to select the ASP.NET Web application type.

Select Web API as the template and in the "Add folders and core references" section, we need to select MVC and Web API. Click on "Change Authentication" on the right side pane and select "No Authentication".

 

In the web.config file, let us define one key named Filepath and use it in our code. The PDF file must be present there.

It is good to change the key's value when it's placed in web.config.
<appSettings> 
     <add key="FilePath" value="Anil\PDF\LDEPRD9.pdf"/> 
 </appSettings> 


Add the below code to the Home Controller.
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString(); 
public ActionResult DownloadFile() 

    try 
    { 
        byte[] bytes = System.IO.File.ReadAllBytes(FilePath); 
        using (MemoryStream inputData = new MemoryStream(bytes)) 
        { 
        using (MemoryStream outputData = new MemoryStream()) 
        { 
        string PDFFilepassword = "123456"; 
        PdfReader reader = new PdfReader(inputData); 
        PdfReader.unethicalreading = true; 
PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS);
        bytes = outputData.ToArray(); 
        Response.AddHeader("content-length", bytes.Length.ToString()); 
        Response.BinaryWrite(bytes); 
        return File(bytes, "application/pdf"); 
       } 
      } 
    } 
    catch (Exception ex) 
    { 
        throw ex; 
    } 


string PDFFilepassword = "123456";   
PdfReader reader = new PdfReader(inputData);   
PdfReader.unethicalreading = true;   
PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS); 


In the PDFFilepassword variable, you can set anything as password - the file name, PAN card number, or you can validate the entered value against the values stored in the database.

In Route.config, we can define the default route with the Controller And ActionName.

Run the website and enter http://localhost:49744/Home/DownloadFile. 

Here, Home is the controller name and DownloadFile is the action name. 

It shows the following Password prompt.

 

After entering the right password and successful authentication, the PDF file will get opened.

HostForLIFE.eu ASP.NET MVC 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Server Sent Events In ASP.NET MVC

clock February 15, 2019 08:14 by author Peter

In some Web Applications, we need to show real time data to the end users, which means if any changes occur (new data available) in the Server, it needs to show an end user. For instance, you are doing chat in Facebook in one tab of your Browser. You opened another tab in the same Browser and send a message to the same user (with whom, you are doing chat in the previous chat). You will see that message will appear in both the tabs and it is called real-time push.

In order to accomplish the functionality, mentioned above, the client sends interval basis AJAX requests to the Server to check, if the data is available or not. ServerSentEvents(SSE) API helps ensure the Server will push the data to the client when the data is available in the Server.

What are Server Sent Events?
SSE is an acronym and stands for Server Sent Events. It is available in HTML5 EventSource JavaScript API. It allows a Web page to get the updates from a Server when any changes occurs in the Server. It is mostly supported by the latest Browsers except Internet Explorer(IE).

Using code
We are going to implement a requirement like there is a link button and click on it and it displays current time each second on an interval basis.
In order to achieve the same, we need to add the following action in HomeController. It sets response content type as text/event-stream. Next, it loops over the date and flushes the data to the Browser.
    public void Message() 
    { 
        Response.ContentType = "text/event-stream"; 
     
        DateTime startDate = DateTime.Now; 
        while (startDate.AddMinutes(1) > DateTime.Now) 
        { 
            Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString())); 
            Response.Flush(); 
     
            System.Threading.Thread.Sleep(1000); 
        } 
         
        Response.Close(); 
    }


Once we are done with the Server side implementation, it's time to add the code in the client side to receive the data from the Server and displays it.

First, it adds a href link, which calls initialize() method to implement SSE. Second, it declares a div, where the data will display. Thirdly, it implements Server Sent Events(SSE) through JavaScript with the steps, mentioned below.
    In the first step, it checks whether SSE is available in the Browser or not. If it is null, then it alerts to the end user to use other Browser.
    In the second step, if SSE is available, then it creates EventSource object with passing the URL as a parameter. Subsequently, it injects the events, mentioned below.

        onopen- It calls when the connection is opened to the Server
        onmessage- It calls when the Browser gets any message from the Server
        onclose- It calls when the Server closes the connection.

    <a href="javascript:initialize();" >Click Me To See Magic</a> 
    <div id="targetDiv"></div> 
     
    <script> 
         
        function initialize() { 
            alert("called"); 
     
            if (window.EventSource == undefined) { 
                // If not supported 
                document.getElementById('targetDiv').innerHTML = "Your browser doesn't support Server Sent Events."; 
                return; 
            } else { 
                var source = new EventSource('../Home/Message'); 
     
                source.onopen = function (event) { 
                    document.getElementById('targetDiv').innerHTML += 'Connection Opened.<br>'; 
                }; 
     
                source.onerror = function (event) { 
                    if (event.eventPhase == EventSource.CLOSED) { 
                        document.getElementById('targetDiv').innerHTML += 'Connection Closed.<br>'; 
                    } 
                }; 
     
                source.onmessage = function (event) { 
                    document.getElementById('targetDiv').innerHTML += event.data + '<br>'; 
                }; 
            } 
        } 
    </script>


Output

Here, we discussed about SSE(Server Sent Events). It is very important API available in HTML5. It helps to push data from the Server to the client when any changes occurs in the Server side. If you want to use a bidirectional communication channel, you can use HTML5 Web Sockets API. The disadvantage of SSE is it is Browser dependent. If the Browser doesn't support SSE, then the user can't see the data, but it is easy to use it. You can also use SignalR for realtime pushing the data to the end user.

HostForLIFE.eu ASP.NET MVC 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



European ASP.NET MVC Hosting :: Basic Routing in ASP.NET MVC

clock January 30, 2019 10:22 by author Scott

When getting started with ASP.NET MVC and/or the ASP.NET Web API, it can be overwhelming trying to figure out how it all works. These frameworks offer powerful features, and abstract away a good deal of pain associated with handling, routing, and responding to HTTP requests within an application. This is a great thing for seasoned developers who understand what it is the framework is doing “for” you (and how to modify that behavior, if desired). It also makes it easier for new or less-experienced folk to set up a basic site or API and watch it “just work.”

On the other hand, the abstraction can make it challenging for those new to the MVC world to understand just what is going on, and where the critical functionality they want to modify “lives.”

One of the fundamental concepts to understand when using ASP.NET MVC and/or the ASP.NET Web API is routing, which essentially defines how your application will process and respond to incoming HTTP requests.

Routing Makes it All Work

Traditional web communication architecture maps a URL (Uniform Resource Locator) to a file within the file system. For example, the following:

http://mydomain.com/mybooks/favorites.html

would tend to map to a file named favorites.html, in the directory ~/mybooks/favorites, located in the root directory for the site mydomain.com. In response to an incoming HTTP request for this resource, the contents of the file are either returned (as in the example above, as HTML) or perhaps code associated with a file is executed (if, for example, the file were a .aspx file).

Within the MVC framework, as well as the Web API*, URLs are instead mapped to specific methods which execute in response to the incoming request, generally returning either a View (MVC) or some sort of structured data (Web API) corresponding to the the requested resource. In other words, instead of pointing to actual physical resources within a file system, MVC and Web API routes instead point to an abstraction which represents the resource requested, in both cases a method which will return the requested item.

This de-coupling of the URL from the physical file system allows us to construct cleaner, more friendly URLs which are more beneficial to the user, search-engine-friendly, and (in theory) more persistent, meaning URLs associated with specific content are less likely to change, and break incoming links. 

How Routing Works in ASP.NET MVC

In MVC, the convention is to map URLs to a particular action (a method) on a particular controller. The action then executes, and (usually, but not always) returns an instance of ActionResult. The ActionResult class handles Framework logic such as rendering to HTML or JSON, and writing to the HTTP response that will be returned to the user’s browser.

Once again, I defer to the authors of ASP.NET MVC 4 (who happen to also be members of the ASP.NET team):

The most basic version of this convention would be a URL as follows:

http://mydomain/controllername/methodname

In an MVC project, this is achieved by registering route templates which establish how incoming URLs will be mapped to specific controllers and actions. A typical MVC project defines a Global.asx file, which contains a single method – Application_Start. Within this method, calls are made to various configuration methods to set up the application’s working state. One of these calls is to the RegisterRoutes method of the RouteConfig class found in the App_Start folder of the project.

Global.asx File and the RouteConfig File in a Typical MVC Project:

If we examine the Global.asx file, we find the following code:

The Default ASP.NET MVC Global.asx File:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

For our purposes, we are interested only in the call to RouteConfig.RegisterRoutes. As we can see, the call passes the the Routes collection of the Global RouteTable as a parameter to the RegisterRoutes method, which then populates the routes collection with pre-defined route templates for the application. The default MVC project template comes with a single pre-configured route:

The Default MVC RouteConfig Class:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
        );
    }
}

Note that any MVC application must have at least one route definition in order to function. In the above, a route template named “Default” is added to the routes collection. The items in curly braces enclose Route Parameters, and are represented by the parameter name as a placeholder between the curly braces. Route Segments are separated by forward slashes (much like a standard URL). Notice how the implied relative URL our route specifies matches the MVC convention:

~/{controller}/{action}

Route parameters can be named just about anything, however ASP.NET recognizes a few special route parameter names, in particular {controller} and {action}, and treats them differently than other route parameters.

Controller Matching

When the routing framework encounters a route parameter named {controller}, it appends the suffix “Controller” to the value of the parameter, and then scans the project for a class by that name which also implements the System.Web.Mvc.IController interface. Note that the search for a controller with a matching name is case-insensitive.

Action Matching

Once the framework has selected the proper controller, it attempts to locate an action on the controller with a name matching the {action} parameter value. The search for a matching action name is case-insensitive. If more than one action matches by name (as with multiple overloaded methods on the same controller), the framework will select the method for which the most URL parameters match method arguments by name.

Action Parameter Matching

Additional URL Parameters other than {controller} and {action} are available to be passed as arguments to the selected Action method. The framework will evaluate the input arguments of the available actions, and match them by name (case-insensitively) to the URL parameters other than {action} and {controller}. With certain restrictions, the framework will select that action with the greatest number of matching parameters.

Some things to consider:

  • The MVC framework will first match method arguments by name to URL parameters. Then, it will attempt to match any query string parameters included in the URL by name. If the request is a POST, then the framework will attempt to match the contents of the POST body.
  • Method arguments are evaluated for a match by name only. The framework does not consider the type required by the method argument. For example, a URL parameter named {id} with a value of “John” will be considered a match for a method which accepts an int argument named id.
  • Action methods can be decorated with attributes which restrict the type of HTTP request they will respond to. Such attributes indicate the applicable HTTP verb to which the action will respond.

As an example of limiting the HTTP actions which a method may respond, consider the following:

Overloaded Action Method with HttpPost Attribute:

public ActionResult Edit(int id)
{
    return View();
}
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        // TODO: Add update logic here
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}
 

In the above, we find two methods named Edit. The first accepts an int named id as an argument, and the second accepts an int named id and a FormCollection (a complex type). The purpose of this overloaded method is so that a browser can:

  • Request a view with which to edit a record of some sort and then,
  • Submit the modified record values back to the site for storage.

The first Edit method, which requires only an int id argument will be called using HTTP GET, and return a view with the current representation of the data to be edited. Once the user has updated values in the view and submits the form data, an HTTP POST request is issued. The overloaded Edit method, decorated with the [HttpPost] attribute, is executed, and the modified data is persisted or otherwise processed. 

The MVC Default Route Template – Routing Walk-Thru

The route mapping assumes that the URL template specified is relative to the domain root for your site. In other words, since the entire application is hosted at http://yourdomain.com it is not necessary to include this domain root as part of the route template.

In the case of the default MVC mapping from our RouteConfig class above, the route contains the two special parameters, {controller} and {action}. In processing incoming requests, the framework appends “Controller” to the value provided for the {controller} parameter, and then searches the project for a controller class of that name. Once the proper controller has been identified, MVC next looks for a method name corresponding to the value of the {action} parameter, and then attempts to match any additional parameters with input arguments accepted by that method.

For example, if our application receives a request with the following URL:

http://mybookstore.com/books/details/25

the routing will match the default template. The string “Controller” will be appended to the “books” segment, and the runtime will set about searching the project for a class named BooksController. If the controller is located, MVC will then examine the controller for a public method named Details. If a Details method is found, MVC will attempt to find an overload which accepts a single argument named id, and then calls that method, passing in the final URL segment (“25” in this case) as an argument.

The following controller example would provide a suitable match for our incoming request:

A Simple Books Controller:

public class BooksController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult Details(int id)
    {
        return View();
    }
}

The incoming request would result in a call to the Details method, passing in the integer 25 as the proper id argument. The method would return the appropriate view (how MVC does this is another convention for another post – let’s stay focused on request routing for now).

Route Parameter Defaults

Notice in the RegisterRoutes method, the registration of the “Default” route also appears to assign some default values to the controller and action, parameters. These values will be used for any of these parameters if they are missing from the incoming request URL. Additionally, the id parameter is designated as optional. For example, consider the following URL:

http://mybookstore.com/books/

In this case, we have specified the Books controller, but have not specified a value for the action or id. However, this route still matches our route definition, since MVC will provide the default value specified for the action parameter (in this case, index). Since the id parameter has been made optional in our route template, MVC will again search for a controller named BooksController, but in this case, examine the controller for a method named Index which does not require an argument. Again, a match is found, and the Index method is called, returning an appropriate view (most likely a list of all the books in the database).

The MVC default route mapping also specifies a default controller to use when no controller parameter is specified; namely, the “Home” controller. In other words, incoming requests to our domain root:

http://mybookstore.com/

will also match the default project controller. In this case, the runtime will attempt to locate a controller named HomeController, then locate the Index method of that controller. Since no id parameter was provided, the Index method will be called, returning the appropriate view ( most likely, the Homepage of our site).

What Next?

As we have seen above, MVC examines an incoming URL and attempts to map each URL segment to a controller and action according to the route templates set up in the RouteConfig.MapRoutesmethod. Once a proper controller and action have been identified, any additional URL segments (for example, the optional {id} segment in our example above) are evaluated against the action method signature to determine the best parameter match for the action.

But what happens when we need to do more than just send an ID in as an argument for the desired action method? Or, what if we have one or more overloaded methods by which we wish to perform more complex queries against our data?

While we can always include query parameters as part of our URL (and in fact we will no doubt have to resort to this at various points in our application design), we can customize and extend the default routing, and exert a little more control over how how and what our application will accept in an HTTP request by customizing our routes.

While the default /controller/action/id route baked into the MVC project template is a useful start and will handle many common controller cases, it is safe to say the MVC team did not expect developers to limit their applications to this minimally-flexible, single standard. Indeed, the ASP.NET routing framework (and the corresponding routing framework used by Web API) are very flexible, and within certain limits, highly customizable.



European ASP.NET MVC Hosting :: Basic Routing in ASP.NET MVC

clock January 30, 2019 10:22 by author Scott

When getting started with ASP.NET MVC and/or the ASP.NET Web API, it can be overwhelming trying to figure out how it all works. These frameworks offer powerful features, and abstract away a good deal of pain associated with handling, routing, and responding to HTTP requests within an application. This is a great thing for seasoned developers who understand what it is the framework is doing “for” you (and how to modify that behavior, if desired). It also makes it easier for new or less-experienced folk to set up a basic site or API and watch it “just work.”

On the other hand, the abstraction can make it challenging for those new to the MVC world to understand just what is going on, and where the critical functionality they want to modify “lives.”

One of the fundamental concepts to understand when using ASP.NET MVC and/or the ASP.NET Web API is routing, which essentially defines how your application will process and respond to incoming HTTP requests.

Routing Makes it All Work

Traditional web communication architecture maps a URL (Uniform Resource Locator) to a file within the file system. For example, the following:

http://mydomain.com/mybooks/favorites.html

would tend to map to a file named favorites.html, in the directory ~/mybooks/favorites, located in the root directory for the site mydomain.com. In response to an incoming HTTP request for this resource, the contents of the file are either returned (as in the example above, as HTML) or perhaps code associated with a file is executed (if, for example, the file were a .aspx file).

Within the MVC framework, as well as the Web API*, URLs are instead mapped to specific methods which execute in response to the incoming request, generally returning either a View (MVC) or some sort of structured data (Web API) corresponding to the the requested resource. In other words, instead of pointing to actual physical resources within a file system, MVC and Web API routes instead point to an abstraction which represents the resource requested, in both cases a method which will return the requested item.

This de-coupling of the URL from the physical file system allows us to construct cleaner, more friendly URLs which are more beneficial to the user, search-engine-friendly, and (in theory) more persistent, meaning URLs associated with specific content are less likely to change, and break incoming links. 

How Routing Works in ASP.NET MVC

In MVC, the convention is to map URLs to a particular action (a method) on a particular controller. The action then executes, and (usually, but not always) returns an instance of ActionResult. The ActionResult class handles Framework logic such as rendering to HTML or JSON, and writing to the HTTP response that will be returned to the user’s browser.

Once again, I defer to the authors of ASP.NET MVC 4 (who happen to also be members of the ASP.NET team):

The most basic version of this convention would be a URL as follows:

http://mydomain/controllername/methodname

In an MVC project, this is achieved by registering route templates which establish how incoming URLs will be mapped to specific controllers and actions. A typical MVC project defines a Global.asx file, which contains a single method – Application_Start. Within this method, calls are made to various configuration methods to set up the application’s working state. One of these calls is to the RegisterRoutes method of the RouteConfig class found in the App_Start folder of the project.

Global.asx File and the RouteConfig File in a Typical MVC Project:

If we examine the Global.asx file, we find the following code:

The Default ASP.NET MVC Global.asx File:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

For our purposes, we are interested only in the call to RouteConfig.RegisterRoutes. As we can see, the call passes the the Routes collection of the Global RouteTable as a parameter to the RegisterRoutes method, which then populates the routes collection with pre-defined route templates for the application. The default MVC project template comes with a single pre-configured route:

The Default MVC RouteConfig Class:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
        );
    }
}

Note that any MVC application must have at least one route definition in order to function. In the above, a route template named “Default” is added to the routes collection. The items in curly braces enclose Route Parameters, and are represented by the parameter name as a placeholder between the curly braces. Route Segments are separated by forward slashes (much like a standard URL). Notice how the implied relative URL our route specifies matches the MVC convention:

~/{controller}/{action}

Route parameters can be named just about anything, however ASP.NET recognizes a few special route parameter names, in particular {controller} and {action}, and treats them differently than other route parameters.

Controller Matching

When the routing framework encounters a route parameter named {controller}, it appends the suffix “Controller” to the value of the parameter, and then scans the project for a class by that name which also implements the System.Web.Mvc.IController interface. Note that the search for a controller with a matching name is case-insensitive.

Action Matching

Once the framework has selected the proper controller, it attempts to locate an action on the controller with a name matching the {action} parameter value. The search for a matching action name is case-insensitive. If more than one action matches by name (as with multiple overloaded methods on the same controller), the framework will select the method for which the most URL parameters match method arguments by name.

Action Parameter Matching

Additional URL Parameters other than {controller} and {action} are available to be passed as arguments to the selected Action method. The framework will evaluate the input arguments of the available actions, and match them by name (case-insensitively) to the URL parameters other than {action} and {controller}. With certain restrictions, the framework will select that action with the greatest number of matching parameters.

Some things to consider:

  • The MVC framework will first match method arguments by name to URL parameters. Then, it will attempt to match any query string parameters included in the URL by name. If the request is a POST, then the framework will attempt to match the contents of the POST body.
  • Method arguments are evaluated for a match by name only. The framework does not consider the type required by the method argument. For example, a URL parameter named {id} with a value of “John” will be considered a match for a method which accepts an int argument named id.
  • Action methods can be decorated with attributes which restrict the type of HTTP request they will respond to. Such attributes indicate the applicable HTTP verb to which the action will respond.

As an example of limiting the HTTP actions which a method may respond, consider the following:

Overloaded Action Method with HttpPost Attribute:

public ActionResult Edit(int id)
{
    return View();
}
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        // TODO: Add update logic here
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}
 

In the above, we find two methods named Edit. The first accepts an int named id as an argument, and the second accepts an int named id and a FormCollection (a complex type). The purpose of this overloaded method is so that a browser can:

  • Request a view with which to edit a record of some sort and then,
  • Submit the modified record values back to the site for storage.

The first Edit method, which requires only an int id argument will be called using HTTP GET, and return a view with the current representation of the data to be edited. Once the user has updated values in the view and submits the form data, an HTTP POST request is issued. The overloaded Edit method, decorated with the [HttpPost] attribute, is executed, and the modified data is persisted or otherwise processed. 

The MVC Default Route Template – Routing Walk-Thru

The route mapping assumes that the URL template specified is relative to the domain root for your site. In other words, since the entire application is hosted at http://yourdomain.com it is not necessary to include this domain root as part of the route template.

In the case of the default MVC mapping from our RouteConfig class above, the route contains the two special parameters, {controller} and {action}. In processing incoming requests, the framework appends “Controller” to the value provided for the {controller} parameter, and then searches the project for a controller class of that name. Once the proper controller has been identified, MVC next looks for a method name corresponding to the value of the {action} parameter, and then attempts to match any additional parameters with input arguments accepted by that method.

For example, if our application receives a request with the following URL:

http://mybookstore.com/books/details/25

the routing will match the default template. The string “Controller” will be appended to the “books” segment, and the runtime will set about searching the project for a class named BooksController. If the controller is located, MVC will then examine the controller for a public method named Details. If a Details method is found, MVC will attempt to find an overload which accepts a single argument named id, and then calls that method, passing in the final URL segment (“25” in this case) as an argument.

The following controller example would provide a suitable match for our incoming request:

A Simple Books Controller:

public class BooksController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult Details(int id)
    {
        return View();
    }
}

The incoming request would result in a call to the Details method, passing in the integer 25 as the proper id argument. The method would return the appropriate view (how MVC does this is another convention for another post – let’s stay focused on request routing for now).

Route Parameter Defaults

Notice in the RegisterRoutes method, the registration of the “Default” route also appears to assign some default values to the controller and action, parameters. These values will be used for any of these parameters if they are missing from the incoming request URL. Additionally, the id parameter is designated as optional. For example, consider the following URL:

http://mybookstore.com/books/

In this case, we have specified the Books controller, but have not specified a value for the action or id. However, this route still matches our route definition, since MVC will provide the default value specified for the action parameter (in this case, index). Since the id parameter has been made optional in our route template, MVC will again search for a controller named BooksController, but in this case, examine the controller for a method named Index which does not require an argument. Again, a match is found, and the Index method is called, returning an appropriate view (most likely a list of all the books in the database).

The MVC default route mapping also specifies a default controller to use when no controller parameter is specified; namely, the “Home” controller. In other words, incoming requests to our domain root:

http://mybookstore.com/

will also match the default project controller. In this case, the runtime will attempt to locate a controller named HomeController, then locate the Index method of that controller. Since no id parameter was provided, the Index method will be called, returning the appropriate view ( most likely, the Homepage of our site).

What Next?

As we have seen above, MVC examines an incoming URL and attempts to map each URL segment to a controller and action according to the route templates set up in the RouteConfig.MapRoutesmethod. Once a proper controller and action have been identified, any additional URL segments (for example, the optional {id} segment in our example above) are evaluated against the action method signature to determine the best parameter match for the action.

But what happens when we need to do more than just send an ID in as an argument for the desired action method? Or, what if we have one or more overloaded methods by which we wish to perform more complex queries against our data?

While we can always include query parameters as part of our URL (and in fact we will no doubt have to resort to this at various points in our application design), we can customize and extend the default routing, and exert a little more control over how how and what our application will accept in an HTTP request by customizing our routes.

While the default /controller/action/id route baked into the MVC project template is a useful start and will handle many common controller cases, it is safe to say the MVC team did not expect developers to limit their applications to this minimally-flexible, single standard. Indeed, the ASP.NET routing framework (and the corresponding routing framework used by Web API) are very flexible, and within certain limits, highly customizable.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Creating Cascading DropDownList In ASP.NET MVC

clock January 23, 2019 10:46 by author Peter

I have used Entity Framework to fetch the values and used Database First approach. I would also write an article on an Entity Framework but today, I would just show you how to bind the cascading dropdown list in this blog.

I have two dropdownlists. One is for state and the other for city. I would populate the city, which is based on the state selection. You can add as many dropdownlists, as you want. For simplicity, I am using only two dropdowns.

Create table scripts
tblState
    CREATE TABLE [dbo].[tblState]( 
        [stateid] [int] NOT NULL, 
        [statename] [nvarchar](50) NULL, 
    PRIMARY KEY CLUSTERED  
    ( 
        [stateid] ASC 
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
    ) ON [PRIMARY] 
     
    GO  

tblCity

    CREATE TABLE [dbo].[tblCity]( 
        [Cityid] [int] NOT NULL, 
        [CityName] [nvarchar](50) NULL, 
        [stateid] [int] NOT NULL 
    ) ON [PRIMARY] 
     
    GO 
     
    ALTER TABLE [dbo].[tblCity]  WITH CHECK ADD FOREIGN KEY([stateid]) 
    REFERENCES [dbo].[tblState] ([stateid]) 
    GO 
 

I have tblState and tblCity, where I have stateid as Primary key in the tblState table and stateid as the Foreign key in tblCity table. You can insert states and cities from the database as you wish.

Now, with Entity Framework; create your EDMX file. In my case, I have named it ModelDemo.edmx.

Model
I have created a Model and named it Registration. This is not directly required but since I used a strongly typed View, so I have created Model. You can also add Model because if you write the httppost method to save the values to the database, then you would need the model.
    public class Registration 
    { 
    [Required(ErrorMessage = "Enter State")] 
            public string State { get; set; } 
    [Required(ErrorMessage = "Enter City")] 
            public string City { get; set; } 
    }  


Controller
Now, this is my Controller code.
    [HttpGet] 
    public ActionResult Details() 
            { 
                bindState(); 
                return View(); 
            } 
    -------------------------------- 
    public void bindState() 
            { 
                var state = objEF.tblStates.ToList(); 
                List<SelectListItem> li = new List<SelectListItem>(); 
                li.Add(new SelectListItem { Text = "--Select State--", Value = "0" }); 
     
                foreach (var m in state) 
                { 
     
     
                    li.Add(new SelectListItem { Text = m.statename, Value = m.stateid.ToString() }); 
                    ViewBag.state = li; 
     
                } 
            } 
    ---------------------------------- 
    public JsonResult getCity(int id) 
            { 
                var ddlCity = objEF.tblCities.Where(x => x.stateid == id).ToList(); 
                List<SelectListItem> licities = new List<SelectListItem>(); 
     
                licities.Add(new SelectListItem { Text = "--Select State--", Value = "0" }); 
                if (ddlCity != null) 
                { 
                    foreach (var x in ddlCity) 
                    { 
                        licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() }); 
                    } 
                } 
                return Json(new SelectList(licities, "Value", "Text", JsonRequestBehavior.AllowGet)); 
            }  


Now, if you see my Controller code, I have a httpget method Details(). I am then calling a non-action method bindState() to bind the state ddl. On selection of the state ddl, the getCity() method will be called to bind the city ddl. I have used jQuery to get the Id of the selected item and have passed it to the getCity method to get the cites for the selected state.

I have also used LINQ to get my desired select value w.r.t the Id passed.

View
Right click on action method Details(), followed by clicking Add View. I always prefer a strongly typed View and I have also created a strongly typed View in this case. The name of my View is Details.cshtml.

You need jQuery min.js. Just download it from the NuGet Package, if it’s not there.

    <script src="~/Scripts/jquery-1.10.2.min.js"></script> 
    <script type="text/javascript"> 
         
        $(document).ready(function () { 
     
            $("#State").change(function () { 
                $("#City").empty(); 
                $.ajax({ 
                    type: 'POST', 
                    url: '@Url.Action("getcity")', 
                    dataType: 'json', 
                    data: { id: $("#State").val() }, 
                    success: function (city) { 
     
                        $.each(city, function (i, city) { 
                            $("#City").append('<option value="' 
                                                       + city.Value + '">' 
                                                 + city.Text + '</option>'); 
                        }); 
                    }, 
                    error: function (ex) { 
                        alert('Failed.' + ex); 
                    } 
                }); 
                return false; 
            }) 
        }); 
    </script>  


I have added the jQuery-min.js. From the code given above, we get the Id of the state ddl.

    <div class="form-group"> 
    @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" }) 
                <div class="col-md-10"> 
                    @Html.DropDownListFor(model => model.State, ViewBag.state as List<SelectListItem>, new { style = "width: 200px;" }) 
     
                    @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" }) 
                </div> 
            </div> 
     
            <div class="form-group"> 
     @Html.LabelFor(model => model.City, htmlAttributes: new { @class =     "control-label col-md-2" }) 
                <div class="col-md-10"> 
          @Html.DropDownListFor(model => model.City, new SelectList(string.Empty, "Value", "Text"), "--Select City--", new { style = "width:200px" }) 
     
                    @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" }) 
                </div>   


I have used jQuery to get the ID of the state DDL on .change function and passed it to bind the city ddl.

Now, just run your Application and you should get the output given below and if you do not get it, then check that if you are getting any values in an Id in getCity() method. If not, then check for Id mis-match.

HostForLIFE.eu ASP.NET MVC 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Call Ajax Method Call with ASP.NET MVC?

clock January 8, 2019 11:41 by author Peter

In this tutorial, let me show you how to call ajax method in ASP.NET MVC.
Controller code here
    [HttpGet] 
    public JsonResult GetAjaxData(string newCode) { 
        return Json(new { 
            Status = "Ajax called succesfully", Message = "Message show succesfully" 
        }, JsonRequestBehavior.AllowGet); 
    } 

View Code Here

    @ { 
        ViewBag.Title = "Index"; 
    } < script src = "~/Scripts/jquery-1.8.2.js" > < /script> 
    <script> 
    function AjaxCall() 
    { 
    $.ajax({ 
    async: false, 
    url: $('#ajaxURL').val(), 
    type: 'GET', 
    cache: false, 
    data: { 
    newCode : "Put the data here" 
    }, 
    success: function (result) { 
    if(result.Status !=''){ 
    alert(result.Status); 
    } 
    else{ 
    alert('Ajax called failed'); 
    } 
    }, 
    error: function (result, textStatus, errorThrown) { 
    alert(errorThrown); 
    } 
    }) 
    } 
    </script > < div > < button value = "Ajax Called" 
    id = "btncalled" 
    onclick = "AjaxCall()" > Ajax Called < /button> 
    </div > @Html.Hidden("ajaxURL", Url.Action("GetAjaxData", "Demo")) 

App_Start-> route config.cs code here

    public static void RegisterRoutes(RouteCollection routes) { 
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
        routes.MapRoute( 
        name: "Default", 
        url: "{controller}/{action}/{id}", 
        defaults: new { 
            controller = "Demo", action = "Index", id = UrlParameter.Optional 
        }); 
    } 


I hope it works for you! Good luck!

HostForLIFE.eu ASP.NET MVC 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



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