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 :: 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.



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