European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Attribute Routing Overview in MVC and .NET Core

clock September 4, 2024 08:36 by author Peter

Attribute routing is a potent feature in ASP.NET Core that lets you explicitly define routing information on controller activities. Compared to traditional routing, this offers more flexibility and control over how HTTP requests are routed to your API endpoints. This is a summary of attribute routing's functions and how to use it in your.NET Core API.


Attribute Routing: What is It?

With attribute routing, you may use attributes to construct routes directly on your action methods or controllers. This method can help make routing easier to comprehend and control because it is more explicit.

How to use Attribute Routing?
1. Basic Attribute Routing

You can apply routing attributes directly to action methods and controllers. For example.

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    // GET api/products
    [HttpGet]
    public IActionResult GetAllProducts()
    {
        // Implementation
    }
    // GET api/products/5
    [HttpGet("{id}")]
    public IActionResult GetProductById(int id)
    {
        // Implementation
    }
    // POST api/products
    [HttpPost]
    public IActionResult CreateProduct([FromBody] Product product)
    {
        // Implementation
    }
}


Controller Route: [Route("api/[controller]")] sets the base route for all actions in the controller. [controller] is a placeholder that gets replaced with the name of the controller (e.g., Products).
Action Routes: [HttpGet], [HttpGet("{id}")], [HttpPost] specify the HTTP methods and the routes for the actions.

2. Route Parameters
You can use route parameters in the attribute routing to capture values from the URL.

[HttpGet("search/{query}")]
public IActionResult SearchProducts(string query)
{
    // Implementation
}

Route Parameter: {query} in the route template will capture the value from the URL and pass it to the action method.

3. Optional Parameters
To make route parameters optional, use the following syntax.
[HttpGet("items/{id?}")]
public IActionResult GetItemById(int? id)
{
    // Implementation
}


Optional Parameter: {id?} makes the id parameter optional.

4. Route Constraints
You can add constraints to route parameters to enforce specific patterns.
[HttpGet("products/{id:int}")]
public IActionResult GetProductById(int id)
{
    // Implementation
}

Route Constraint: {id:int} ensures that the id parameter must be an integer.

5. Route Prefixes and Constraints at Controller Level
You can also set route prefixes and constraints at the controller level.
[ApiController]
[Route("api/[controller]/[action]")]
public class OrdersController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAllOrders()
    {
        // Implementation
    }

    [HttpGet("{id:int}")]
    public IActionResult GetOrderById(int id)
    {
        // Implementation
    }
}

Action Route: [action] is replaced with the action method name in the route URL.

6. Combining Routes
You can combine routes and use route templates to create complex routing scenarios.
[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    [HttpGet("{customerId}/orders/{orderId}")]
    public IActionResult GetCustomerOrder(int customerId, int orderId)
    {
        // Implementation
    }
}

Benefits of Attribute Routing
Clarity and Control: Route definitions are more explicit and closely related to their corresponding actions, making it easier to understand and manage routes.
Flexibility: Allows for more complex routing scenarios, including optional and default parameters, constraints, and combined routes.
Customization: Facilitates precise control over route templates and endpoints.

Combined Route
The route combines customerId and orderId parameters to define a more specific endpoint.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How to Centralize Modal Popups in .NET MVC to Simplify Code and Enhance?

clock August 26, 2024 06:55 by author Peter

Several forms to manage modal popups can result in repetitive code and more maintenance work. We'll look at how to centralize modal popup code in a.NET MVC application in this blog post. This will let you define the modal once and utilize it in other places in your project. We will cover how to create a modal's partial view, add it to various sites, and effectively handle modal triggers. You will have a better structured and manageable method for dealing with modal popups in your.NET MVC apps at the end of this article.


You can centralize the modal popup code and utilize it throughout your application to avoid repeating it in every form. Here's how to go about it.

Establish a Partial Model View
The modal code can be included in a partial view that you design. You can add this partial view to any page that requires a modal.

Steps
Create Partial View
Right-click on the Views/Shared folder (or any other folder) and select Add -> View.
Name the view _DeleteModal.cshtml.
In the view, add the modal code.

    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <asp:Label ID="ltrlDelHead" Text="Are You Sure, You want to Delete This?" runat="server"></asp:Label>
                </h5>
                <button type="button" class="bootbox-close-button close" data-dismiss="modal" aria-hidden="true">×</button>
            </div>
            <div class="modal-body">
                <div class="bootbox-body">
                    <div class="bootbox-form"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link" data-dismiss="modal">Cancel</button>
                <asp:LinkButton ID="lnkRecordDelete" class="btn bg-danger" runat="server" OnClick="lnkRecordDelete_Click">Delete</asp:LinkButton>
            </div>
        </div>
    </div>

Include Partial View in Your Pages
In any view where you want to use this modal, simply include the partial view.
@Html.Partial("_DeleteModal")


Alternative Using Layout or Master Page
If you need this modal on many pages, you can add the modal code directly to your layout or master page so it’s available throughout your application.

Steps

Open your Layout.cshtml (or master page if using WebForms).
Add the modal code before the closing </body> tag.

<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
   @Html.Partial("_DeleteModal")
</div>


Then, use JavaScript or server-side logic to trigger this modal when needed.

Triggering the Modal
To trigger the modal from different parts of your application, you can use JavaScript or server-side code to open it when required.
$('#deleteModal').modal('show');

This approach centralizes the modal code, making your application more maintainable and easier to manage. Now, you only need to update the modal in one place if any changes are required.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Learn About Action Selectors In ASP.NET MVC

clock August 13, 2024 08:42 by author Peter

Nearly all of the information you need to know about action selectors in ASP.NET MVC action methods is covered in this article. I'm producing this post to explain to you the most important, fundamental, and advanced ideas of action selectors.

Overview and Context
The characteristics that can be added to action methods to affect the choice of action method are known as action selectors. Which action methods are called in response to an HTTP request are determined by action selectors. As you may have observed in my earlier post, "MVC Architecture and its Pipeline," under the "Pipeline in MVC" section, the HTTP request first reaches "Routing," then "Controller Initialization," and finally "Action Execution." The rendering of the view is thereby limited to the "Result Execution." Action selectors are used in the section titled "Action Execution" and are crucial in determining which action method is best for handling a given HTTP request. Now let's examine action methods.

Which action methods are there?
The controller's action methods are those whose names must coincide with the method names in the request URL. Following the execution of the request, these methods produce the response. A controller may have numerous action methods. Additionally, you can designate a controller's default action method for handling requests.

What do you mean by action selectors?
A certain action method needs to be chosen in the answer to a request sent to the routing engine. Therefore, action selectors are in charge of choosing this course of action. Because of the attribute applied above the action method, the action selector does its job. Let's examine the many kinds of action selectors.

Types of action selectors
There are three types of action selectors

  • NonAction
  • ActionName
  • ActionVerbs

Name of Action
An action selector called the [ActionName] attribute is used to change the name of the action method. When we want that action method to be called by a different name than the method's real name, we utilize the [ActionName] attribute. The example that follows shows you how to use an action method that was originally named "Time." Let's make the ActionSelectorsDemo project. Choose "Visual C#," then "ASP.NET Web Application," then give the project a name and click "OK."

Select “Empty” and mark “MVC” then click OK, as shown below.

The project is created successfully. Now, create a Controller as shown below.

Select the type of Controller as “MVC 5 Controller – Empty” and click “Add”.

Then, give the name of the Controller and click “Add”.

Make the following changes in the Index action method of the HomeController, as shown below in the screenshot.

Now, the project is ready to take a look at a practical example of [ActionName] action selector. Now, let’s add an action method with the name of “Time” whose purpose is to print the current time. See the code below.

public String Time() {
    return @"Current Time is: " + DateTime.Now;
}

When you build and run the application with this /Home/Time URL, you should see the following output.

Now we are going to use the [ActionName] attribute with the “Time” action method. See the code below.
[ActionName("GetTime")]
public String Time() {
    return @"Current Time is: " + DateTime.Now;
}

Now build and run the application with this /Home/Time URL, you should see the following error, it is because of the [ActionName] action selector.

By using this action selector, you have changed the name of the action method, now the URL /Home/GetTime only works instead of /Home/Time. See the output below.

Hence you have seen that the [ActionName] action selector can change the name of the action method.

NonAction

[NonAction] attribute is an action selector that indicates a public method of the controller is not an action method. We use the [NonAction] attribute when we want a method that shouldn’t be treated as an action method.

As you know, the Controller contains the methods that are public and are termed action methods because of one-to-one mapping with the HTTP-requested URL. But when you want that, any method of Controller shouldn’t be treated as an action method, then you have to use the [NonAction] attribute.

Example
Now let’s make some changes in the HomeController of ActionSelectorsDemo project. Add another method named “GetTimeMethod” whose responsibility is also to print the current time. And then call this newly added method into the “Time” action method. You can see the code of both action methods below.
[ActionName("GetTime")]
public String Time() {
    return GetTimeMethod();
}
public String GetTimeMethod() {
    return @"Current Time is: " + DateTime.Now;
}


Now observe the output, after building and running the application. When we run the application with this /Home/Time URL, we’ll see an error because we are bound to use the name “GetTime” for this action method because of the [ActionName] action selector. Now when you run the application with this /Home/GetTimeMethod, you should see the output given below.

As you have seen, you are still able to access GetTimeMethod while there is no need to access it because it is producing the same output as produced by the “GetTime” action method. So we need to restrict its access by using the [NonAction] action selector because it makes the method a non-action method. So it can’t be called in the request URL at all. Let’s see its example. The code of the “GetTimeMethod” method will become as follows.

[NonAction]
public String GetTimeMethod() {
    return @ "Current Time is: " + DateTime.Now;
}


So the output will become.


So as you have seen, the [NonAction] action selector is used to make an action method Non-Action method.

ActionVerbs

You have seen in the beginning of this article what actions are. And you should also know “Verbs” which are defined as “words which are used to describe an action, state or occurrence of an event”. So as the name suggests, “ActionVerbs” can be defined as “the words that describe the action, purpose, and state of the action method of a Controller”. Now, let’s move towards its technical explanation.

When an HTTP request comes to the controller on a specific action method, then this selector helps us to select the correct action method based on the HTTP requested method. It also helps us to create more than one action method with the same name, also referred to as overloading. So to differentiate these action methods, we use action verbs. We’ll see its example later in this article.

MVC framework supports different ActionVerbs, shown as follows.

  • HttpGet: It is used to get information from the server. When this applies to the action method, it restricts the action method to accept only HTTP GET requests.
  • HttpPost: It is used to post information on the server. When this applies to the action method, it restricts the action method to accept only HTTP POST requests.
  • HttpPut: It is used to create or replace existing information on the server, but can’t update. And when this applies to the action method, it restricts the action method to accept only HTTP PUT requests.
  • HttpDelete: It is used to delete any existing information from the server. When this applies to an action method, it restricts the action method to accept only HTTP Delete requests.
  • HttpPatch: It is used to fully or partially update any existing information on the server. When this applies to the action method, it restricts the action method to accept only HTTP Patch requests.
  • HttpOptions: It is used to represent information about the options of the communication that are supported by the web server.


Action verbs are very popular in using APIs. In the MVC framework, if you don’t apply any attribute of the action selector on the top of the action method when the method is called from the HTTP request, then that HTTP request will behave like a HttpGet request by default.

Conclusion
I hope this article has helped you understand all the concepts of action selectors in ASP.NET MVC. And stay tuned for my next article. If you have any queries then feel free to contact me in the comments section. Also, giving feedback, either positive or negative, will help me to make my articles better and increase my enthusiasm to share my knowledge.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Behavior of Session States Per Action in ASP.NET MVC

clock July 25, 2024 09:28 by author Peter

We can regulate the session state behavior in ASP.NET MVC with the aid of the SessionState Attribute. Using this property, we may set the session state to read-only, required, or disabled for the controller. We can only use this attribute at the controller level because it is a class level attribute. A controller's action methods may behave differently from the controller session state behavior in some cases. The following solution is quite helpful in this situation. Thus, in ASP.NET MVC, we may implement a session state behavior for each action.

Problem Synopsis
The SessionState property allows us to regulate the behavior of the session state, however it is only applicable at the controller level. This indicates that the session state behavior is the same for all of the controller's action methods. What is the course of action to take now that certain controller action methods do not require a session while others do?

Resolution
In this case, all the action methods that share the same session state behavior can be moved to a distinct controller class and made. This is a poor course of action. Alternatively, we may override the session state behavior for that particular action method by creating a custom action property.


To create a custom action attribute that overrides the session state's behavior, follow these steps.

First, make a custom attribute.

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]  
    public sealed class ActionSessionStateAttribute : Attribute  
    {  
        public SessionStateBehavior Behavior { get; private set; }   
        public ActionSessionStateAttribute(SessionStateBehavior behavior)  
        {  
            this.Behavior = behavior;  
        }  
    } 


Step 2: Create custom controller factory
    public class CustomControllerFactory : DefaultControllerFactory  
    {  
        protected override SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)  
        {  
            if (controllerType == null)  
            {  
                return SessionStateBehavior.Default;  
            }  
            var actionName = requestContext.RouteData.Values["action"].ToString();  
            MethodInfo actionMethodInfo;  
            actionMethodInfo = controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);  
            if (actionMethodInfo != null)  
            {  
                var actionSessionStateAttr = actionMethodInfo.GetCustomAttributes(typeof(ActionSessionStateAttribute), false)  
                                    .OfType<ActionSessionStateAttribute>()  
                                    .FirstOrDefault();  
       
                if (actionSessionStateAttr != null)  
                {  
                    return actionSessionStateAttr.Behavior;  
                }  
            }  
            return base.GetControllerSessionBehavior(requestContext, controllerType);  
        }  
    }  


Step 3: Register custom controller factory in Global.asax
    protected void Application_Start()  
    {  
        AreaRegistration.RegisterAllAreas();  
        RegisterGlobalFilters(GlobalFilters.Filters);  
        RegisterRoutes(RouteTable.Routes);  
        ControllerBuilder.Current.SetControllerFactory(typeof(CustomControllerFactory));  
    }

Step 4: Attribute usages
    [SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]    
    public class HomeController : Controller    
    {    
        public ActionResult Index()    
        {    
            ViewBag.Message = "Welcome to ASP.NET MVC!";    
            TempData["test"] = "session less controller test";    
            return View();    
        }  
        [ActionSessionState(System.Web.SessionState.SessionStateBehavior.Required)]    
        public ActionResult About()    
        {    
            Session["test"] = "session less controller test";    
            return View();    
        }    
    }




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Sorting Results in ASP.NET Core MVC

clock July 12, 2024 06:43 by author Peter

An action method in ASP.NET Core MVC can return many kinds of outcomes, which are referred to as Action outcomes. What kind of response the controller delivers back to the client is determined by these outcomes. The standard technique for returning results from a controller action method is defined by the IActionResult interface. Let's examine the many kinds of results.

1. ViewResult
This result is used to render a view (HTML page) to the client. It is the most common type used in MVC applications.

Example
public IActionResult Index()
{
    return View();
}

2. JsonResult

This result is used to return JSON-formatted data. It is commonly used for API responses.

Example
public JsonResult GetJsonData()
{
    var data = new { Name = "John", Age = 30 };
    return Json(data);
}

3. ContentResult

This result is used to return plain text or any other content.

Example
public ContentResult GetContent()
{
    return Content("Hello, this is plain text.");
}


4. FileResult

This result is used to return a file to the client, such as a document, image, or any other file.

Example
public FileResult GetFile()
{
    var fileBytes = System.IO.File.ReadAllBytes("path/to/file.pdf");
    return File(fileBytes, "application/pdf", "download.pdf");
}


5. RedirectResult

This result is used to redirect the client to a specified URL.

Example
public RedirectResult RedirectToUrl()
{
    return Redirect("https://www.example.com");
}

6. RedirectToActionResult
This result is used to redirect the client to a specific action method in the controller.

Example
public RedirectToActionResult RedirectToActionMethod()
{
    return RedirectToAction("Index", "Home");
}


7. RedirectToRouteResult
This result is used to redirect the client to a specific route.

Example
public RedirectToRouteResult RedirectToRouteMethod()
{
    return RedirectToRoute(new { controller = "Home", action = "Index" });
}


8. StatusCodeResult
This result is used to return a specific HTTP status code.

Example
public StatusCodeResult GetStatusCode()
{
    return StatusCode(404);
}


9. EmptyResult

This result does not return any content.

Example
public EmptyResult DoNothing()
{
    return new EmptyResult();
}


10. PartialViewResult
This result is used to render a partial view.

Example
public PartialViewResult GetPartialView()
{
    return PartialView("_PartialView");
}


11. ObjectResult

This result is used to return an object as the response. It is often used in APIs to return data along with an HTTP status code.

Example
public ObjectResult GetObject()
{
    var data = new { Name = "John", Age = 30 };
    return new ObjectResult(data) { StatusCode = 200 };
}


Conclusion

ASP.NET Core MVC provides a rich set of action results that allow you to return various types of responses from your controller actions. Each result type serves a specific purpose and can be used to meet the requirements of different scenarios. Understanding these result types is crucial for building robust and flexible web applications.

With these action results, you can efficiently manage how your application responds to client requests, whether it's rendering views, returning JSON data, or handling file downloads.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Managing CRUD Operations in ASP.NET MVC with Razor and C#

clock July 4, 2024 09:56 by author Peter

Creating, reading, updating, and deleting (CRUD) operations are essential functionalities for any web application. In this article, we'll explore how to implement these operations in an ASP.NET MVC application using Razor views and C#.


Controller Actions

Democurd Action
The democurd action is responsible for displaying a list of democurd records.

public ActionResult democurd()
{
    DemoModel model = new DemoModel();
    model.Id = Convert.ToInt32(Session["Id"]);
    var list = demovider.Getdemocurd(model);
    return View(list);
}

  • Initialization: A DemoModel object is created and its Id property is set from a session variable.
  • Data Fetching: The Getdemocurd method of demovider is called to fetch a list of democurd records.
  • Return View: The list of records is passed to the view for display.

democurdAddEdi Action (GET)
The democurdAddEdi action displays a form for adding or editing a democurd record.
public ActionResult democurdAddEdi()
{
    democurdinput model = new democurdinput();
    return View(model);
}

    Model Initialization: A new democurdinput model is initialized.
    Return View: The model is passed to the view for rendering the form.

democurdAddEdi Action (POST)
This action handles the form submission for adding or editing a democurd record.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> democurdAddEdi(democurdinput obj)
{
    try
    {
        if (ModelState.IsValid)
        {
            // Your logic here
            return RedirectToAction("StationMaster");
        }
        else if (obj.StationId != 0)
        {
            var Li = democurdAddvider.democurdAdd(obj);
            if (Li.Status == "0")
            {
                return RedirectToAction("democurd");
            }
            else
            {
                return View(obj);
            }
        }
    }
    catch (Exception ex)
    {
        // Handle exception
    }

    return View(obj);
}

  • Form Validation: Checks if the model state is valid.
  • Condition Handling: Depending on the StationId, it either redirects or returns the view with validation errors.
  • Exception Handling: Catches and handles any exceptions that occur during the process.

Editdemocurd Action

The Editdemocurd action fetches a democurd record for editing.
public ActionResult Editdemocurd(int? id)
{
    democurdinput model = new democurdinput();
    try
    {
        model.dmId = Convert.ToInt32(id);
        var list = democurdvider.Getdemocurd(model);
        var ass = list.FirstOrDefault();
        return PartialView("StationMasterAddEdi", ass);
    }
    catch (Exception ex)
    {
        // Handle exception
    }
    return View("democurdAddEdi", null);
}

    Model Initialization: A new democurdinput model is initialized with the id parameter.
    Data Fetching: Retrieves the record to be edited using the Getdemocurd method.
    Return Partial View: The record is passed to a partial view for editing.

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <div class="card-title">
                        <i class="icon-layers"></i> Manage democurd
                        <span class="pull-right">
                            <a href="@Url.Action("methodname", "controllername")" class="btn btn-primary mt-ladda-btn ladda-button btn-circle" data-style="expand-right">
                                <span class="ladda-label">
                                    <i class="fa fa-plus"></i> Add
                                </span>
                            </a>
                        </span>
                    </div>
                    <div class="preview-list">
                        <table class="table table-striped table-bordered dt-responsive nowrap" id="dataTableModules1">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Number</th>
                                    <th>val</th>
                                    <th>valtude</th>
                                    <th>status</th>
                                    <th>StatusDesc</th>
                                    <th>wstg</th>
                                    <th class="text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var i in Model)
                                {
                                    <tr>
                                        <td>@i.Name</td>
                                        <td>@i.Number</td>
                                        <td>@i.val</td>
                                        <td>@i.valtude</td>
                                        <td>@i.status</td>
                                        <td>@i.StatusDesc</td>
                                        <td>@i.wstg</td>
                                        <td class="text-center">
                                            <a href="@Url.Action("Editdemocurd", "Master", new { id = @i.Id })" class="btn btn-success btn-fw" data-style="expand-right">
                                                <span class="ladda-label">
                                                    <i class="fa fa-pencil-square-o"></i>
                                                </span>
                                            </a>
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

Table Structure: The table includes columns for various attributes of the democurd records and an action column for editing.
Add Button: A button to add a new record, redirecting to the StationMasterAddEdi action.

JavaScript for DataTable and Alerts

JavaScript code to initialize DataTable and display success or failure alerts.

@section scripts {
    @{
        if (TempData["AlertError"] != null)
        {
            <script>
                swal("Failure", "@TempData["AlertError"].ToString()", "error");
            </script>
        }
        if (TempData["AlertSuccess"] != null)
        {
            <script>
                swal("Success", "@TempData["AlertSuccess"].ToString()", "success");
            </script>
        }
    }
}


<script>
    $(document).ready(function () {
        window.showLoading({ name: 'jump-pulse', allowHide: true });
        $('#dataTableModules1').dataTable({
            autoWidth: false,
            responsive: true,
            "bLengthChange": true,
            "bFilter": true,
            "language": {
                "searchPlaceholder": "Search"
            },
            "aaSorting": [],
            "sPaginationType": "full_numbers",
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'copyHtml5',
                    text: '<i class="fa fa-files-o"></i> Copy',
                    titleAttr: 'Copy'
                },
                {
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i> Excel',
                    titleAttr: 'Excel'
                },
                {
                    extend: 'csvHtml5',
                    text: '<i class="fa fa-file-text-o"></i> CSV',
                    titleAttr: 'CSV'
                },
                {
                    extend: 'pdfHtml5',
                    text: '<i class="fa fa-file-pdf-o"></i> PDF',
                    titleAttr: 'PDF'
                }
            ]
        });
        setTimeout(function () {
            window.hideLoading();
        }, 1000);
    });
</script>

  • Alerts: Displays success or failure alerts based on TempData values.
  • DataTable Initialization: Initializes the DataTable with specific options and buttons for exporting data.

Form for Adding or Editing democurd Records
A form for adding or editing democurd records with validation and anti-forgery protection.
@using (Html.BeginForm("democurdAddEdi", "democontroller", FormMethod.Post, new { id = "__AjaxAntiForgeryForm", role = "form", LoadingElementId = "please-wait" }))
{
    @Html.AntiForgeryToken()
    <div class="form-body">
        <div class="row">
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">Station Name<span class="text-danger">*</span></label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.Name, new { placeholder = "Enforcement Name", @class = "form-control", onkeypress = "return onlyAlphabets(this, event);", maxlength = "100", @required = true })
                        @Html.HiddenFor(m => m.StationId)
                        <span class="help-block">@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">Mobile Number<span class="text-danger">*</span></label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.Number, new { placeholder = "Number", @class = "form-control", onkeypress = "return onlyNumber(this, event);", maxlength = "10", minlength = "10", @required = true })
                        <span class="help-block">@Html.ValidationMessageFor(m => m.Number, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">val<span class="text-danger">*</span></label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.val, new { placeholder = "val", @class = "form-control", onkeypress = "return onlyNumberwithDot(this, event);", maxlength = "100", @required = true })
                        <span class="help-block">@Html.ValidationMessageFor(m => m.val, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">valtude<span class="text-danger">*</span></label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.valtude, new { placeholder = "valtude", @class = "form-control", onkeypress = "return onlyNumberwithDot(this, event);", maxlength = "100", @required = true })
                        <span class="help-block">@Html.ValidationMessageFor(m => m.valtude, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">status</label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.status, new { placeholder = "status", @class = "form-control", @required = true })
                        <span class="help-block">@Html.ValidationMessageFor(m => m.status, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
            <div class="form-actions noborder pull-right">
                <a href="@Url.Action("methodname", "controllername")" class="btn btn-danger btn-flat"><i class="fa fa-ban fa-fw"></i>Cancel</a>
                <button id="btnSubmit" type="submit" class="btn btn-info btn-flat"><i class="fa fa-save fa-fw"></i>Submit</button>
            </div>
        </div>
    </div>
}


Conclusion
In this article, we've covered the implementation of CRUD operations in an ASP.NET MVC application using Razor views and C#. We explored the various controller actions responsible for listing, adding, and editing records. Additionally, we discussed the Razor views for displaying the records in a table and providing forms for user input.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Performance Optimization in ASP.NET MVC Applications

clock June 27, 2024 08:03 by author Peter

Performance optimization for ASP.NET MVC (Model-View-Controller) applications use a range of techniques in an effort to improve the efficiency, responsiveness, and speed of applications created using this framework. The following are some key areas and methods for optimizing the performance of ASP.NET MVC applications.

1. Efficient data access
Use Entity Framework wisely: Optimize queries, use lazy loading carefully, and prefer compiled queries for frequently used data access paths.
Stored Procedures: Use stored procedures for complex and frequently run queries to reduce the overhead of query parsing and execution planning.
Caching: Implement caching strategies like output caching, data caching, and distributed caching (e.g., using Redis) to reduce database load.

2. Optimizing server-side code
Async/Await: Use asynchronous programming (async/await) to handle I/O-bound operations without blocking threads.
Minimize ViewState: Reduce the use of ViewState to decrease the payload size.
Bundling and Minification: Combine and minify CSS and JavaScript files to reduce the number of HTTP requests and the size of requested resources.
Compression: Enable GZIP compression in IIS to compress the response data sent to the client, reducing the response size.

3. Efficient use of resources
Pooled Connections: Use connection pooling to reuse database connections.
Memory Management: Properly manage memory usage to avoid excessive garbage collection and memory leaks.
Thread Pooling: Utilize thread pooling to manage a pool of worker threads, which can be reused for executing tasks, reducing the overhead of thread creation.

4. Front-end performance
Lazy Loading: Implement lazy loading for images and other resources to load them only when they are in the viewport.
Content Delivery Network (CDN): Use CDNs to serve static resources like images, CSS, and JavaScript files from locations closer to the user, reducing latency.
Browser Caching: Set appropriate caching headers to enable browsers to cache static resources.

5. Optimizing Queries and Data Access
Indexing: Properly index database tables to improve query performance.
Pagination: Implement pagination for data-heavy views to load only a subset of data at a time.
Query Optimization: Analyze and optimize LINQ queries to reduce execution time.

6. Application Monitoring and Profiling
Application Insights: Use tools like Azure Application Insights for monitoring and diagnostics to identify performance bottlenecks.
Profiling Tools: Use profiling tools to analyze the performance of your application and identify hotspots.

7. Configuration and Deployment

Configuration Settings: Tune application settings such as session state management, request timeouts, and garbage collection modes.
Scalability: Design the application to be scalable, allowing it to handle increased load by adding more resources (horizontal scaling) or optimizing resource usage (vertical scaling).

8. Load Balancing
Load Balancers: Use load balancers to distribute incoming traffic across multiple servers, ensuring no single server is overwhelmed.
Session State Management: Ensure the session state is managed in a distributed manner (e.g., using a distributed cache) to support load balancing.

Example implementation
Here’s an example of how to implement output caching in an ASP.NET MVC controller.

using System.Web.Mvc;
public class HomeController : Controller
{
    [OutputCache(Duration = 60, VaryByParam = "none")]
    public ActionResult Index()
    {
        return View();
    }
}

In this example, the OutputCache attribute is applied to the Index action method, caching the output for 60 seconds.

Conclusion

By implementing these strategies, you can significantly improve the performance of your ASP.NET MVC application. Each application is unique, so it's important to profile and monitor your specific application to identify the most effective optimization techniques.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Integrate Twilio in C# ASP.NET Core MVC Project to Send SMS

clock June 21, 2024 08:38 by author Peter

There are a ton of in-app notifications, everyone uses a ton of websites and apps every day, communication is crucial in today's fast-paced environment. But those in-app alerts won't appear until we launch the program. Therefore, adding SMS functionality to projects could greatly increase user interaction and engagement. Among other communication services, Twilio, a well-known cloud communications company, offers developers a robust API that makes it simple to send and receive SMS texts.


This post will explain how to incorporate Twilio into a C# MVC project from scratch in order to send SMS. So let's get started on the project by first creating a Twilio account.

Setting up a Twilio account
To set up a Twilio account, we will first sign up, and that's quite easy. If you already have a Twilio account, you can skip step 1 and just follow from step 2.

Step 1. Sign Up in Twilio

Sign up by filling in the basic details on the following link - www.twilio.com. By clicking on "Continue," you will be redirected to another page to verify your email. Once the email is verified, you will need to verify your phone number as well. After that, you will be redirected to another page that will provide a recovery code. Please copy the code and keep it somewhere safe for future use.

Step 2. Log in to Twilio
If you are logging in for the first time, Twilio will ask you a few questions. Just answer them, and it will take you to the dashboard, which will look like below.

 

Step 3. Get the Phone Number
Click on the "Get Phone Number" button, and you will receive the number. Before purchasing their plan, your account will be a trial account, and the number given to you will be a trial number.

Step 4. Get SID and Auth Token
In the same screen, you will have a section named "Account Info", where you will following information -Account SID, Auth Token, and My Twilio phone number, which we will be using during development.

Step 5. Verify Phone Numbers
This step is only for trial account users. Since it is a trial account, you will need to verify the numbers on which you want to send the SMS using your project. You can skip this step if you have purchased a Twilio SMS plan. To verify numbers, follow the following steps.

  • Click on the verified phone numbers link. You will be redirected to another page.
  • Click on the "Add a new caller ID" button in the right corner. A popup will open to add the number.
  • Select the country, number, and mode through which you want to verify the number.
  • Click verify the number, you will get an OTP on the number you just entered.
  • Enter the OTP to verify the number and it will be shown in verified caller IDs.

Now that you have set up the Twilio account. Let's move to the project.

Setting up the project

You can either create a new project or you can integrate Twilio into an existing project. Here, I have created a demo project to integrate Twilio in it and created a Controller named "TwilioIntegrationController". In this controller, I will be writing Twilio-related code. Let's move to the project.

Step 1. Install dependencies
To be able to integrate Twilio in the project, you will need some dependencies, that will help Twilio run.

  • Click on Tools.
  • Select "Nuget Package Manager".
  • Click "Manage Nuget Package for solution".
  • In the Browse section, search for Package "Twilio" and install the solution.
  • Then, search "Twilio.AspNet.Mvc" and install it too.

Now that you have installed all the necessary dependencies. Let's move to the next step.

Step 2. Code to Send SMS

In the "TwilioIntegrationController", write your code for sending SMS. Here, I am putting all my code in one file. But you should put the necessary code where it should be.
using Microsoft.AspNetCore.Mvc;
using Twilio;
using Twilio.Rest.Api.V2010.Account;

namespace TwilioIntegration.Controllers
{
public class TwilioIntegrationController : Controller
{
    [Route("send-SMS")]
    public IActionResult SendSMS()
    {
        string sId = ""; // add Account from Twilio
        string authToken = ""; //add Auth Token from Twilio
        string fromPhoneNumber = "+120*******"; //add Twilio phone number

        TwilioClient.Init(sId, authToken);
        var message = MessageResource.Create(
            body: "Hi, there!!",
            from: new Twilio.Types.PhoneNumber(fromPhoneNumber),
            to: new Twilio.Types.PhoneNumber("+9175********") //add receiver's phone number
        );
        Console.WriteLine(message.ErrorCode);
        return View(message);
    }
}
}

Code Explanation
In the above code,

  • Add 'using Microsoft.AspNetCore.Mvc;', 'using Twilio;', 'using Twilio.Rest.Api.V2010.Account;' to use Twilio API in the code.
  • Then, I have created a method named SendSMS().
  • In the method, I created three string variables - sId, authToken, and fromPhoneNumber to store Twilio account SId, Auth Token, and Twilio phone number. I have placed all three in this method, but you should store them in an appsettings file and access them from there.
  • Then, initiate TwilioClient by passing your account SId and Auth Token using this lineTwilioClient.Init(sId, authToken);.
  • In the next line "MessageResource.Create()" is a method call to create a new SMS message using the Twilio API. It indicates that we are creating a new message resource. We are passing the message body, from phone number and to phone number in it. It creates the message and sends it using the Twilio API.
  • In the next line, I have consoled the ErrorCode, if any error occurs during the sending of SMS.
  • If you got this exception while executing the method, Permission to send an SMS has not been enabled for the region indicated by the 'To' number. Click here to resolve this- solution

Step 3. Call the above method
Call the method that we created earlier from your code to send SMS from wherever you want in your code, and Twilio will send the SMS to the account that you mentioned earlier.

In the above image, you can see the message is sent successfully from the project and the body is the same as we mentioned in our code. But as we are using a trial account, hence, Twilio adds the prefix "Sent from your Twilio trial account-" in all the messages that you will send from your trial account. Hence, for real-life projects, it is better to buy a plan.

Conclusion

In this article, we have seen how to create a Twilio account, set it up, and integrate Twilio with the code in the C# MVC project. By following simple steps to set up a Twilio account and implementing Twilio's API, developers can easily send and receive SMS messages, offering a valuable tool for improving project functionality and user experience.

Like this, you can also integrate Twilio in other languages too. The process is almost similar. You can also use Twilio to send WhatsApp messages and voice messages, etc by simply integrating it into your project. This integration empowers developers to leverage Twilio's robust cloud communication platform to enhance their projects across various programming languages, facilitating effective communication and user engagement.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Dependency Injection In ASP.NET MVC 5

clock June 11, 2024 09:26 by author Peter

I was inspired to produce an article about utilizing Dependency Injection in ASP.NET MVC5 after reading many ones about it in MVC and C#.


In MVC, Dependency Injection (DI)

One way to put "Inversion of Control" into practice is through dependency injection. According to the theory known as Inversion of Control (IoC), objects obtain the objects they require from an external source (such as an XML configuration file) rather than creating other objects that they depend on to do their tasks.

Let's now put the same into practice.
Create a new project for ASP.NET MVC.

No, install the "Unity.Mvc5" Container using NuGet Package Manager, as shown below.

When it is installed successfully, you will find the following two references added to your project and a UnityConfig.cs class file in App-Start folder.

Now, let’s create the repository that will be accessed by the Controller.

  • Add a folder named Repository.
  • Add an interface IUserMasterRepository.

interface IUserMasterRepository
    {
        IEnumerable<UserMaster> GetAll();
        UserMaster Get(int id);
        UserMaster Add(UserMaster item);
        bool Update(UserMaster item);
        bool Delete(int id);
    }

Now, add the repository which has your data access code.
public class UserMasterRepository : IUserMasterRepository
{
    private List<UserMaster> users = new List<UserMaster>();
    private int Id = 1;

    public UserMasterRepository()
    {
        // Add products for the Demonstration
        Add(new UserMaster { Name = "User1", EmailID = "[email protected]", MobileNo = "1234567890" });
        Add(new UserMaster { Name = "User2", EmailID = "[email protected]", MobileNo = "1234567890" });
        Add(new UserMaster { Name = "User3", EmailID = "[email protected]", MobileNo = "1234567890" });
    }

    public UserMaster Add(UserMaster item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }

        item.ID = Id++;
        users.Add(item);
        return item;
    }

    public bool Delete(int id)
    {
        users.RemoveAll(p => p.ID == id);
        return true;
    }

    public UserMaster Get(int id)
    {
        return users.FirstOrDefault(x => x.ID == id);
    }

    public IEnumerable<UserMaster> GetAll()
    {
        return users;
    }

    public bool Update(UserMaster item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }

        int index = users.FindIndex(p => p.ID == item.ID);
        if (index == -1)
        {
            return false;
        }
        users.RemoveAt(index);
        users.Add(item);
        return true;
    }
}

Note. Here, we have used a repository. You can use services which will consume your Repository.
Now, register this repository to container in UnityConfig.cs.
    public static void RegisterComponents()
    {
        var container = new UnityContainer();
        container.RegisterType<IUserMasterRepository, UserMasterRepository>();
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
Add UnityConfiguration in AppStart method of Global.asax
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    UnityConfig.RegisterComponents();
}

Inject the Dependency in Controller.

Create UserController

Now, in the below code, we have created a constructor of UserContoller, injected the UserMasterRepository, and accessed it in Index action.

public class UserController : Controller
{
    readonly IUserMasterRepository userRepository;

    public UserController(IUserMasterRepository repository)
    {
        this.userRepository = repository;
    }

    // GET: User
    public ActionResult Index()
    {
        var data = userRepository.GetAll();
        return View(data);
    }
}


Add a View for the same.
Add User folder in Views folder.
Add Index View.

Below is the code which needs to be written in Index View file.

@model IEnumerable<MVCWithDI.Repository.UserMaster>

@{
    ViewBag.Title = "Users";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmailID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MobileNo)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EmailID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MobileNo)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>


Now, run the project. Here is the output.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Consuming Web Service In ASP.NET MVC

clock May 27, 2024 07:50 by author Peter

In order to transfer information, web services are still crucial in many modern applications. Because of my well-received series of articles on ASP.NET Web Services from two or three years ago, people have been requesting that I publish a straightforward piece on how to use Web Services in MVC applications. I have therefore chosen to produce an essay on ASP.NET MVC about using Web Services based on that requirement. We will learn how to use Web Services in ASP.NET MVC applications in this tutorial.

Step 1. Create MVC Application

  • "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
  • Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project; whatever name you wish, and click OK.
  • After clicking, the Window given below will appear. Choose an empty project template and check the MVC option.

The preceding step creates the simple empty ASP.NET MVC Application without a Model, View, and Controller. The Solution Explorer of the created Web Application will look as shown below.

Step 2. Adding Web Service reference
There are many ways to consume Web Services but in this article, we will learn to consume the Web Service by using the Add Service reference method. Note. We are using Web Services, which are hosted in IIS. For more details, please watch my video by using the link given in the prerequisites section. The URL is given below, hosted by Service, which we are going to use in this application .

http://localhost:8080/PaymentWebService.asmx

Right-click on the created ASP.NET MVC Application and click Add Service Reference, as shown below.

Now, after clicking on the preceding Service reference option, it will show the Window given below.

Now, click on the advanced button. It shows the Window given below, which allows us to configure how the entities and output should behave.

After configuring the appropriate Service reference settings, click Add Web Service reference. It will show the Window given below.

As shown in the preceding image, our Web Service found two web service methods which are highlighted with a red rectangle. Now provide the web service reference name as you wish and click on ok , it will add the Web Service reference in our created ASP.NET MVC application, as shown below.

As you can see in the preceding highlighted square section, the Web Service reference gets added to our created ASP.NET MVC application. Now, we are done with adding the Web Service reference.

Step 3. Add Controller Class
Now, let us add the ASP.NET MVC controller, as shown in the screenshot given below.

After clicking the Add button, it will show in the Window. Specify the Controller name as Home with the suffix Controller. Now, let's modify the default code of the Home controller. After modifying the code of Homecontroller class, the code will look, as shown below.

Home controller. cs
using System.Linq;
using System.Web.Mvc;

namespace ConsumingWebServiceInASPNETMVC.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult BookingStatus()
        {
            //Creating Web Service reference object
            HotepBookingPayReference.PaymentWebService objPayRef = new HotepBookingPayReference.PaymentWebService();

            //calling and storing web service output into the variable
            var BookingStatusInfo = objPayRef.RoomBookingStatus().ToList();
            //returning json result
            return Json(BookingStatusInfo, JsonRequestBehavior.AllowGet);
        }
    }
}


I hope, you have gone through the same steps and understood how to use and call ASP.NET Web Service.

Step 4. Create Empty View
Now, right-click on the Views folder of the created Application and create View, which is named by Index, to display hotel booking details from hosted ASP.NET Web Services, as shown below.

Now, click the Add button. It will create a View named index. Now, modify the code and write the jQuery function to bind the HTML table, using JSON data after modifying the default code. The code snippet of the Index View looks, as shown below.

Index. cshtml
@{
    ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.intellisense.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $.getJSON("/Home/BookingStatus", function (data) {
            var tr;
            $.each(data, function (d, i) {
                tr = $('<tr/>');
                tr.append("<td>" + i.RoomId + "</td>");
                tr.append("<td>" + i.RooType + "</td>");
                tr.append("<td>" + i.BookingStatus + "</td>");
                $('#tblBookingStatus').append(tr);
            });
        });
    });
</script>

<p class="form-horizontal">
    <hr />
    <p class="form-group">
        <table id="tblBookingStatus" class="table table-responsive" style="width:400px">
            <tr>
                <th>
                    Room Id
                </th>
                <th>
                    Room Type
                </th>
                <th>
                    Booking Status
                </th>
            </tr>
            <tbody>
            </tbody>
        </table>
    </p>
</p>


The preceding View will display all hotel booking details. Now, we have done all the coding.

Step 5. Run the Application
After running the Application, the hotel booking details from hosted ASP.NET Web Service will look, as shown below.

I hope, from the above examples, you have learned how to consume ASP.NET Web Services in ASP.NET MVC Applications.

Note

Download the zip file of the published code to learn and start quickly.
This article is just a guideline on how to consume ASP.NET Web Service in ASP.NET MVC Applications.
In this article, the optimization is not covered in depth; do it as per your skills.

Summary

I hope this article is useful for all the readers. If you have any suggestions, please mention them in the comments section.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in