Handle back-slash “\” in Razor View and JavaScript

We are passing following view bag value;

ViewBag.Alphabets = "a\\b\\c";

We are retrieving this value in JavaScript in Razor view;

console.log('@ViewBag.Alphabets');

JS Output
console.log('a\b\c');

Console Output
a_c

Where did the “\” goes? Since this is a part of escape characters so JS automatically removes “\\” and replaced it with “_”. “\b” is a metacharacter so it’s gone as well.

We can fix it by using Replace command on ViewBag.

console.log('@ViewBag.Alphabets.Replace("\\", "\\\\")');

JS Output
console.log('a\\b\\c;');

Console Output
a\b\c

References

https://www.tutorialspoint.com/escape-characters-in-javascript

Pass data to controller using jQuery

We want to pass some data from jQuery to ASP.NET Core / MVC. We have an action method “AddEmployee” in Home controller and we want to pass input values to the controller.

$(document).ready(function () {
        $("#btnSave").click(function () {
            var formData = new FormData();
            //Reading text box values using Jquery)
            formData.append('Name', $("#txtName").val(); 
            formData.append('City',$("#txtAddress").val());
            formData.append('Address',$("#txtcity").val());
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/AddEmployee", // Controller/View 
                //url: '@Url.Action("AddEmployee", "Home")',
                data: { //Passing data
                    formData
                },
                //cache: false,
                //processData: false,
                //contentType: false,

                success: function (data) {
                    alert("success...any incoming data");
                },
                failure: function (data) {
                    alert("failure....");
                }
            });
        });
    });

Alternatively we can have seperate functions for success and failure actions;

function btnSaveSuccess(data)
{
  alert('success');
}

function btnSaveFailure(data)
{
  alert('failure');
}

We can call these functions in btnSave main function sucess/failure blocks.

To work with jQuery we need to reference of jQuery library .You can use following CDN jQuery libraryfrom any provider such as Microsoft,Google or jQuery .

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 

To use jQuery library you need an active internet connection , You can download and use it as offline .You need to be add reference as like below.

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

ASP.NET Web Site or ASP.NET Web Application?

Website:

The Web Site project is compiled on the fly. You end up with a lot more DLL files, which can be a pain. It also gives problems when you have pages or controls in one directory that need to reference pages and controls in another directory since the other directory may not be compiled into the code yet. Another problem can be in publishing.

If Visual Studio isn’t told to re-use the same names constantly, it will come up with new names for the DLL files generated by pages all the time. That can lead to having several close copies of DLL files containing the same class name, which will generate plenty of errors. The Web Site project was introduced with Visual Studio 2005, but it has turned out not to be popular.

Web Application:

The Web Application Project was created as an add-in and now exists as part of SP 1 for Visual Studio 2005. The main differences are the Web Application Project was designed to work similarly to the Web projects that shipped with Visual Studio 2003. It will compile the application into a single DLL file at build time. To update the project, it must be recompiled and the DLL file published for changes to occur.

Another nice feature of the Web Application project is it’s much easier to exclude files from the project view. In the Web Site project, each file that you exclude is renamed with an excluded keyword in the filename. In the Web Application Project, the project just keeps track of which files to include/exclude from the project view without renaming them, making things much tidier.

Reference

The article ASP.NET 2.0 – Web Site vs Web Application project also gives reasons on why to use one and not the other. Here is an excerpt of it:

  • You need to migrate large Visual Studio .NET 2003 applications to VS 2005? use the Web Application project.
  • You want to open and edit any directory as a Web project without creating a project file? use Web Site project.
  • You need to add pre-build and post-build steps during compilation? use Web Application project.
  • You need to build a Web application using multiple Web projects? use the Web Application project.
  • You want to generate one assembly for each page? use the Web Site project.
  • You prefer dynamic compilation and working on pages without building entire site on each page view? use Web Site project.
  • You prefer single-page code model to code-behind model? use Web Site project.

Web Application Projects versus Web Site Projects (MSDN) explains the differences between the web site and web application projects. Also, it discusses the configuration to be made in Visual Studio.

Reference

https://stackoverflow.com/questions/398037/asp-net-web-site-or-asp-net-web-application

Search string array in collection using LINQ

LINQ behavior is that LINQ wouldn’t return null when results are empty rather it will return an empty enumerable. We can check this with .Any() method;

if (!YourResult.Any())

This is a LinqPad example;

var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );

(ans == null).Dump();  // False
(ans.Count() == 0 ).Dump();  // True

Let’s go through another example where I have this string array to search;
{“dog”,”cat”};

in this string;
“This is a string and may or may not contain a word we are looking for like cat”

string input = "This is a string and may or may not contain a word we are looking for like cat";
List<string> search = new List<string>() { "dog", "cat"};
bool found = input.Split(' ').Any(x => search.Contains(x));

It works like this: the string gets split into an array of words. Then Any checks whether there is an x in this array where search.Contains(x).

Enumerable.Any(TSource) Method (IEnumerable(TSource)) (System.Linq)

Reference

What does linq return when the results are empty

Find all items in list which exist in another list using linq

Hide/Show Div with javascript

To display and hide DIV in html;

<div class="card-body">
   <div id="divMessage">                
        @Html.Raw(@TempData["message"]);
    </div>
    </div>  
    <div> 
       <!--need to hide this form-->         
       <form method="post" asp-antiforgery="true" id="formDiv">
          <div class="card mb-3">
             <h5 class="card-header text-white">
                  Welcome To Div Hide/Display
             </h5>
        </form>
    </div>
</div>

Use this javascript;

@section Scripts
{
  <script>
     $(document).ready(function () {
            //show/hide login sections based on SSO
            divFormSection();
        });

        function divFormSection() {
            var isDivFormVisible = '@TempData["IsDivFormVisible"]';
            if (isDivFormVisible == 'false') {
                //alert(isDivFormVisible);
                $("#formDiv").hide();
            }
        }
     }
    </script>
}

We need to pass parameters from controller in TempData;

TempData["message"] = "Form Hide/Display demo";
TempData["IsDivFormVisible"] = "false";