Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. Show all posts

Wednesday, January 15, 2020

ASP.NET MVC : How to display error message from controller to view

This blog explain how to show validation error in MVC View from Controller.

There is different ways to pass error message from controller to View

·         ModelState
·         ViewBag

Use AddModelError() method of ModelState  to display error message :

Model State is a Key/Value dictionary, which is used to store state of Model, which is posed from Action and it includes validation information for each fields.

It expose the main properties/method, with help of this, you can validate the posted model by calling IsValid Property, if Model has any failed validation, it return false otherwise true .

if (ModelState.IsValid)
            { 
                // Call further API/Service or business object 
            }
            else
            { 
                // Show error message 
            }

You can add validation error message by using AddModelError() method and you can use @Html.ValidationSummary() to display the validation message on view, basically  the ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and it can be used to display all the error messages for all the fields. It can also be used to display custom error messages

[HttpPost]

public ActionResult SavePerson(Person model)
{
  string Name = model.Name;   
  int firstOccurance = Name.IndexOf(',');
  int lastOcuurance =  Name.LastIndexOf(',');

  if (firstOccurance == 0)
  {
     ModelState.AddModelError("Name", "Name should not begin with Comma ','.");
  }
  else if (lastOcuurance == Name.Length - 1)
  {
     ModelState.AddModelError("Name", "Name should not end with Comma ','.");
  }

 return View("Person", person);
}

HTML Razor View:

@model Person
@Html.ValidationSummary()
<div>
    <div class="row">
        <div class="col-sm-12">
            @Html.Partial("_Person", Model })
        </div>
    </div>
</div>

HTML View:

ASP.NET MVC VALIDATION ERROR MESSAGE


Use Viewbag to display Error Message:

ViewBag is used to send data from controller to view and to display the error message, we can also use the ViewBag to transfer error or validation message from controller to view.

MVC Controller:

[HttpPost]

     public IActionResult SavePerson(Person person)
        {           
            string Name = person.Name;
            int firstOccurance = Name.IndexOf(',');
            int lastOcuurance = Name.LastIndexOf(',');

            if (firstOccurance == 0)
            {
                ViewBag.ErrorMessage = "Name should not begin with Comma ','.";
               // ModelState.AddModelError("Person.Name", "Name should not begin with Comma ','.");
            }
            else if (lastOcuurance == Name.Length - 1)
            {
                ViewBag.ErrorMessage = "Name should not begin with Comma ','.";
                //ModelState.AddModelError("Person.Name", "Name should not end with Comma ','.");
            }

            return View("Person", person);
        }

HTML Razor View:

<div class="alert alert-danger">
    <p>@ViewBag.ErrorMessage</p>
</div>

Tuesday, March 26, 2019

URL.Action return &amp;in URL

I recently encountered one issue that URL.Action returns &amp; in URL,
Basically URL.Action method, which is used to resolve the qualified URL on based on Controller, Action Name with Route variable data, returns the qualified URL

Here is source code

HTML View:

  <script type="text/javascript">
$.OrderDetailsURL =  '@Url.Action("OrderDetails", "Order", new { orderID =OrderID, Status =Updated })';
  </script>

When you see javaScript variable OrderDetailsURL  value which have &amp ; in place of &


and we are expecting @Url.Action  method should return below URL without &amp ;


There are two ways to overcome this issue.

 1. Use @HTML.Row() – it returns string which are not HTML encoded. 

$.OrderDetailsURL =  '@Html.Raw(@Url.Action("OrderDetails", "Order", new { orderID =OrderID, Status =Updated }))';

 2In JavaScript, Call replace method to update &amp with &

          document.location.href = $. OrderDetailsURL.replace("&","&");

Thanks for visiting!!

Friday, March 15, 2019

ASP.NET MVC Bootstrap Model Dialog: Intermediate exception Model Background is under modal background

I recently encountered this bootstrap modal window problem that the modal dialog window is closed but the background is still in-active and completely blocked.


Here is my scenario, when I opens the model dialog window on click on link and it makes Ajax call to get model data from server. But due to this some delay, user will be allowed to click more than one time, it opens multiple Modal dialog window and I close the modal window , model widow is getting closed but the background screen is still blocked. Screen shot attached for reference 

ASP.NET MVC: Bootstraps Modal Window

ASP.NET MVC: Bootstraps Modal Window

I investigated into this problem and found that when the modal window is getting open, for modal background experience,  it always adds new DIV with modal-backdrop CSS in HTML BODY so background screen is completely blocked and when modal dialog window is closed, it removes this DIV from HTML BODY and the background screen becomes active.

<div class="modal-backdrop fade in"></div>

In my scenario, multiple modal window are being opened and it added more than one DIV in HTML BODY to block the back ground screen and on closing of Modal dialog window it removes only one DIV from HTML body and still there are DIV in HTML BODY to block the Background screen.

To resolve this issue I used the below code to remove all the extra DIV from HTML BODY on closing of Model window.

$(document).on('hidden.bs.modal''.modal'function () {
    if ($(".modal-backdrop").length > -1) {
        $(".modal-backdrop").remove();
    }

});

Monday, December 24, 2018

ASP.NET MVC: HTML.ACTIONLINK VS URL.ACTION

@Html.ActionLink generates anchor  <a> tag or hyperlink on a view page in MVC whereas @Url.Action returns only a qualified URL. 

HTML.Actionlink() : 

HTMLHelper (@Html) object uses ActionLink() method to render the anchor HTML element with specified link text and action /controller name.


Here is an example of HTML.ActionLink() method to generate a hyperlink with action/controller name:

@Html.ActionLink("Home""Home""Person"

It Generates <a href="/Person/Home" >Home</a>

@Html.ActionLink("Product""Detail""Product", new { id ="5668"}, null

It Generates: < a href="https://www.blogger.com/product/detail/5678" > Product </a>


URL.Action ():

URL.Action method is used to generate the qualified URL by using the action and controller name with routes value.

Here is an example of URL.Action() method:

Url.Action("detail", "product", new { id = "5678" })

It Generates:  /product/detail/5678

More information about URL.Action @  MSDN : UrlHelper.Action Method


Friday, December 21, 2018

ASP.NET MVC : Anchor Tag IN MVC Razor View


In this blog we will discuss about the @HTMLHelper class and how to create the HTML Anchor by using @Html.ActionLink.

@HTMLHelper Class:

@Html is used in ASP.NET MVC to render HTML elements like TextBox, Button etc. and it binds the model object to HTML control and display the object’s value and while posting the page, it binds the control value to model object.


@Html.ActionLink Method:

HTMLHelper object has ActionLink method to render the anchor HTML element with specified link text and action name with controller.


Here is examples of Action methods:

·        @Html.ActionLink("Home""Home""Person"

Generates <a href="/Person/Home" >Home</a>


·         IF you are not passing controller, by default it will take current page controller name.


    @Html.ActionLink("Home""Home")


·         Action and Controller with parameter are given:


@Html.ActionLink("Home""Home""Person"new { PersonID = Model.ID}, null )


Generates <a href="../Person/Home?PersonID=1212" >Home</a>


·         Anchor with html ID


@Html.ActionLink("Home""Home""Person"new { PersonID = Model.ID}, new { id = "HomeLinkID"} )


Generates <a href="../Person/Home?PersonID=1212" id="HomeLinkID" >Home</a>

Thanks for visiting!!

Tuesday, October 30, 2018

ASP.NET MVC Exception : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions


{InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions}

I recently encountered above exception, when I tried to bind Data Model to View to show count of Order and here is Code:



HTML View:

<div class="form-group">
            @Html.LabelFor(m => m.PostedOrders)
                <div class="col-md-3">
                    @Html.DisplayFor(m => m. PostedOrders.Count())
                </div>
</div>

If you see exception, it tell, you can only bind @Html.DisplayFor with Field, Property of Model and it does not support function or expression.



To fix this problem, you need to add one additional property or field in Model Class [OrderDataModel] that holds the total count of posted orders and you can bind this field/property with view to display total count of posted order

C# :

public class OrderDataModel
    {
        public List<Order> PostedOrder { get; set; }
        public int Total => PostedOrder.Count;
    }


HTML View:

<div class="form-group">
            @Html.LabelFor(m => m.Total)
                <div class="col-md-3">
                    @Html.DisplayFor(m => m.Total)
                </div>
</div>

Thanks for visiting, please leave your comments if it helps

Monday, June 18, 2018

ASP.NET MVC : OutPutCache Action Filter

The outputCache, inbuilt action filter in MVC, enables you to cache the action result content by a MVC controller action. By default MVC Output cache is enabled. So for this you don’t need to do anything, if client will send same request, browser will not forward request to MVC controller and it returns previous cached result.

There are few major properties of OutPutCache attribute
·         Location
·         NoStore
·         Duration
·         VaryByParm
·         VaryByHeader

OutPutCache Location:

The output cache can be located on the browser client (where the request originated), on a proxy server (or any other server) participating in the request, or on the server where the request was processed. There are following possible values for output cache location and default value is ‘ANY’.
  • Any - the output cache can be located on client browser, proxy server.
  • Client - Cache will be stored on client browser as private.
  • Downstream - The output cache will be stored in any HTTP 1.1 cache-capable devices other than the origin server
  • None - The output cache will be disabled
  • Server - The output cache will be stored on the server where request was handled and processed.
  • ServerAndClient – the output cache will be stored on both server and client browser. 
Here is an example, output cache location is Client.

public class HomeController : Controller

    {
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = System.Web.UI.OutputCacheLocation.Client)]

public ActionResult LoadInfo(int pageNumber)

{

            List<Info> infos = new List<Info>();

            for (int i = 0; i < 10; i++)

            {

                int ivalue = rand.Next();

                Info info = new Info()

                {

                    Header = "Header" + ivalue,

                    InfoBody = "Body",

                };

                infos.Add(info);

            }

            return PartialView("_Info", infos);

}

    }


OutputCache NoStore:

NoStore is Boolean property, which tells that cache value will be stored or not. Default value is true.If NoStore value is true, it prevent the caching your data.

OutputCache Duration:

It tell the time duration (in second) that the cache data is stored.

OutputCache VaryByParm:

This property enables you to create different cached versions of the very same content when a form parameter or query string parameter varies.
  • VaryByParam = “City,CustomerID” :
     It creates different cached versions whenever any of the form or query string parameters in the list “City, CustomerID” varies.

[OutputCache(NoStore = true, Duration = 1000, VaryByParam = " City,CustomerID", Location = System.Web.UI.OutputCacheLocation.Client)]

public ActionResult GetCustomerInfo(int customerID, string city)

{

}

  • VaryByParam = "none" :
If you don’t want to store the Cache data, set VaryByParam = "none" it never cache data and always calls to repository to get data from database.

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "none", Location = System.Web.UI.OutputCacheLocation.Client)]

public ActionResult GetCustomerInfo(int customerID, string city)

{

}
  • VaryByParam = "*" :
It create a different cached version, whenever a form or query string parameters varies

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = System.Web.UI.OutputCacheLocation.Client)]

public ActionResult GetCustomerInfo(int customerID, string city)

{

}

Other related topics 
Thanks for visiting!! 

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...