Posts

Showing posts with the label ASP.NET MVC

Donate

Parse And Replace Element Attribute Value Of Script Template Using jQuery

Good afternoon fellow programmers! I recently have a task to load a Script template that contains HTML markup to a page dynamically. But before loading the template, I need to change the attribute values of certain elements such as id and name. However, reading the template object made it difficult for me to convert it to an HTML object so I can traverse and manipulate the DOM. After doing research and some experiments, I found the solution presented below on how to read the value of a Script template and be able to use jQuery methods to traverse and update the DOM elements. Sample Script Template To Load In A Page <script type= "text/html" id= "templateGroup" > <div name= 'divChildSkill_' class= "col-md-12" id= "divChildSkill_" > <div class= "col-md-12" > <div class= "col-md-6" > <div class= "col-md-4" > <label id= "anchorLabel" >&l

Restrict Remote Validation In ASP.NET MVC Edit Mode.

Hello, In data entry operations, we normally validate user input if they exist in the database, if yes we throw some kind of exception or error message that the data they entered already exists in the database. But in scenario like editing of existing information, we don't want this to happen. So to restrict the remote validation in ASP.NET MVC, I found the fix from stack Remote validation restrict for edit controller method but modified the logic in the controller which is to return a JSON rather than a bool value. The code modifications are as follows. Edit View or Edit Partial View: Add another HiddenField for Initial Product Code used for Comparison. @Html.Hidden("InitProductCode", Model.ProductCode) Model: Add AdditionalFields in Remote Attribute. [Display(Name = "Product Code")] [Required(ErrorMessage = "ProductCode is required")] [Remote("CheckProductCode", "Products", HttpMethod = "POST", ErrorMessage = &q

Bootstrap Modal Hide Not Working On Form Submit In ASP.NET MVC

Good afternoon! I'm working on a ASP.NET MVC which uses the oldest version of Bootstrap which 3.0. Normally when working with modals, the hide() function works if using updated versions of the Bootstrap given the code below. The snippet should close the modal after a form has been submitted but this doesn't work as expected when working with the oldest version. $( "#modal-add" ).on( "submit" , "#form-add" , function (e) { e.preventDefault(); var form = $( this ); $.ajax({ url: form.attr( "action" ), method: form.attr( "method" ), data: form.serialize(), success: function (data) { $( "#modal-add" ).modal( 'hide' ); //close modal function $( "#tblEmployee" ).bootstrapTable( 'load' , data); showAlert( 'Saving of record successful!' , 'success' ); }, error: function (er) { showAlert( 'Error saving record. Please try again later.' , 'dan

Script Selector With Specified Attribute Not Found When Using jQuery In ASP.NET MVC

I have this script below that will insert a dynamically defined script tag next to an existing script element in an ASP.NET MVC page. $(document).ready( function () { script.type = "text/javascript" ; script.src = '/Scripts/bootstrap3.2.0.js' ; $(script).insertAfter( 'script[src*="bootstrap.js"]' ); $( 'script[src*="bootstrap.js"]' ).attr( 'src' , '' ); }); Using the script above, I wasn't able to achieve the output since it can't locate the particular script tag. Upon investigating the production site, it appears that the scripts are bundled and the code above has no effect. With slight modification of the code to check if a script is bundled, I managed to get the inserting of script working. $(document).ready( function () { var script = document.createElement( 'script' ); script.type = "text/javascript" ; script.src = '@Url.Content("~/Scripts/bootstrap3.2.0.js")&

MongoDB Getting UTC Date Instead Of Local Date In ASP.NET MVC

Image
Hello all! When inserting local dates in MongoDB and retrieving them using C#, you might wonder why the date returned is inconsistent with the values stored in the database. Well, MongoDB treats those dates as UTC. So to display those dates as local, there are several solutions. Option one is to change the BsonElement attribute of a date property [BsonElement] [Required(ErrorMessage = "Activity Date required")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime ActivityDate { get ; set ; } to BsonDateTimeOptions and set it's kind to local. [BsonDateTimeOptions(Kind = DateTimeKind.Local)] [Required(ErrorMessage = "Activity Date required")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime ActivityDate { get ; set ; } Option two is to retain the BsonElement attribute of the date property. [BsonElement] [Required(ErrorMessage = "A

Unable to get property call of undefined or null reference (jQuery Validation in ASP.NET MVC)

Hello, Our team encountered this issue before when using jQuery.Validation in ASP.NET MVC and the solution that we have is to replace the jQuery Validation Plugin from version 1.8.0 to 1.11.1 . Until now, were still using this version. Cheers!

Unable To Pass MongoDB's Object ID To Update Controller Action In ASP.NET MVC

When passing a model to the Update action, you may notice that the id field contains series of zeroes instead of the GUID value given the action below. public ActionResult EditActivity (UserActivity userActivity) { if (userActivity != null ) { userRepository.Update(userActivity); } return RedirectToAction ( "Index" ); } I already have set the @Html.HiddenFor() in the page with the value of the ID. After doing some research, I came up with the solution which is to change the @Html.HiddenFor(model => model.Id) element to @Html.Hidden(). @using (Html.BeginForm("EditActivity", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.Hidden("id", Model.Id) //your html form elements here... } And in the controller action, add another parameter for the id which is of type string. public ActionResult EditActivity (UserActivity userActivity, string id) { if (userActivity != null ) { userActivity.Id = ObjectId.Pars

Cannot read property 'DateSorter' of undefined in Bootstrap Table

Good evening gents! Doing some refactoring to one of my projects using the JavaScript prototype pattern, I encountered issues while calling the functions in prototype through the Bootstrap Table by Wenzhixin specifically in the data-sorter property. In document ready, I created an object of an EmployeeModel class that contains the function. $(document).ready( function () { EmployeeObj = new EmployeeModel(); }); And in the data-sorter property, I called the custom function to sort dates. <th data-field= "signout_time" data-sortable= "true" data-searchable= "true" data-sorter= "EmployeeObj.DateSorter" > @Html.DisplayNameFor(model => model.EmployeeList[0].SignOutTime) </th> Doing so, throws an exception "Cannot read property 'DateSorter' of undefined". After further investigation, the table has set values for data-sort-name and data-sort-order properties. <table id= "" data-sort-name=

Custom JavaScript Date Sorter Function For Bootstrap Table in ASP.NET MVC

Image
While working on a project that implements Bootstrap Table by Wenzhixin, one column returns a date value with the format of MMM-YYYY and this column is sortable. A solution I've come up is to use the flexibility of Moment.js. Here's to date sorter function for the column. function DateSorter(a, b) { var dateA = new Date(moment(a).format( 'MMM-YYYY' )); var dateB = new Date(moment(b).format( 'MMM-YYYY' )); if (dateA < dateB) return -1; if (dateA > dateB) return 1; return -0; } Then set the data-sorter property of the table column with the function name. <th data-field= "BillingMonth" data-sortable= "true" data-sorter= "DateSorter" >Billing Month</th> Output Sample Fiddle: Custom JavaScript Date Sorter Function For Bootstrap Table Using Moment.JS

jQueryUI Datepicker Works Only Once In ASP.NET MVC Partial View

Lately while working in an ASP.NET MVC project, i encountered a problem that when I load a partial view for the first time, the jQueryUI DatePicker shows up. However after loading the partial view for the second time and so on, the DatePicker does not show up. I've tried several approaches and solutions presented in the net. And the fix that worked on my end was to: 1. Change the id of the textbox control to which the DatePicker has been initialized to something unique.      txtAddHireDate for add partial view      txtEditHireDate for edit partial view 2. Remove the referencing of the jquery and jqueryUI library of each partial view and transferred them to Index.cshtml(Index.cshtml loads these partial views). That's it.

Data Annotation Validation Of TimeSpan Property In Model Using RegularExpression Attribute

Hello, To validate a model property of type TimeSpan using Data Annotation RegularExpression attribute, the expressions should check the hours, minutes and seconds since the corresponding database column in SQL Server that is mapped with this field has a Time data type. The example below validates a 23 hour format military time and does not allow minutes or seconds greater than zero. [RegularExpression(@"^(?:[01][0-9]|2[0-3]):[0-0][0-0]:[0-0][0-0]$ ", ErrorMessage =" Invalid time format and hh:mm:ss values. ")]

Bootstrap Table JavaScript Data-Sorter For Currency Column

Image
If your Bootstrap Table by Wenzhixin has a string currency column with a dollar sign and you want to sort the amount which disregards the currency symbol, a solution would be to remove the currency symbol and comma using Regex in JavaScript. function AmountSorter(a, b) { var billA = Number (a.replace( /(^\$|,)/g , '' )); var billB = Number (b.replace( /(^\$|,)/g , '' )); if (billA < billB) return - 1 ; if (billA > billB) return 1 ; return - 0 ; } And in your Bootstrap Table column, set the data-sorter property with the name of your currency sorter function. <th data-field= "RegistrationFee" data-sortable= "true" data-sorter= "AmountSorter" > Registration Fee </th> Output Sample Fiddle: Bootstrap Table JavaScript Data-Sorter For Currency Column

Filtering, Paging and Searching Bootstrap Table in ASP.NET MVC

Image
Good afternoon! The previous two articles on using Bootstrap Tables by Wenzhixin were simply displaying, sorting and paging records. This tutorial will demonstrate on how apply filtering features to the table. First is to create an ASP.NET MVC project and then add an ADO.NET Entity Data Model that will use the Northwind Database Employees table. Next is to add an EmployeeView model that will be used as field names by the Bootstrap Table. The source code for the View Model and the EmployeeController is presented can be copied from this article Sort Bootstrap Table Date Column By Wenzhixin Using Moment.js In ASP.NET MVC . To enable filtering of the table, obtain the bootstrap-table-filter-control.js from the Bootstrap Table source code at github and reference it in your page as presented below: <link href= "~/Content/bootstrap.min.css" rel= "stylesheet" /> <link href= "~/Content/bootstrap-table.css" rel= "stylesheet" /> <script

Sort Bootstrap Table Date Column By Using Moment.js In ASP.NET MVC

Image
Hello, In this tutorial, I'll demonstrate on how to sort a date column of a Bootstrap Table by Wenzhixin using Moment.js. First is to create an empty ASP.NET MVC project and then add an ADO.NET Entity Model that references the Employee table of Northwinds database. Next is to define an Employee ViewModel class that will hold the information to be utilized by the Bootstrap table. public class EmployeeViewModel { public int EmployeeID { get ; set ; } public string EmployeeName { get ; set ; } public DateTime BirthDate { get ; set ; } public DateTime HireDate { get ; set ; } public string Address { get ; set ; } public string PostalCode { get ; set ; } public string Country { get ; set ; } } Then add a new controller called Employee that declares a Northwind context object, queries the database and returns the model object as JSON. public class EmployeeController : Controller { private NorthwindEntities _context; public EmployeeController() { _con

Using Bootstrap Table Wenzhixin With ASP.NET MVC

Image
Good evening guys and gals! In this tutorial, I will show you on how to display records in tabular format using Bootstrap Table created by Wenzhixin in ASP.NET MVC. First, you need to have AdventureWorks Database since this is the database used in the demo. Next is to create an ASP.NET MVC project and then add an ADO.NET Entity Model that targets the AdventureWorks DB specifically the tables People , EmployeeDepartmentHistories , Departments , Shifts , BusinessEntityAddresses and Addresses . Proceed by adding an EmployeeViewModel class that contains properties of the Employee. This class will be used by the Bootstrap Table's columns property. public class EmployeeViewModel { public int BusinessEntityId { get ; set ; } public string EmployeeName { get ; set ; } public string Address { get ; set ; } public string PostalCode { get ; set ; } public string DepartmentName { get ; set ; } public string DepartmentGroupName { get ; set ; } public string Shif

Chrome Script Debugging In Visual Studio Is Enabled Hangs Up

Image
Good morning! While using the Visual Studio 2017 to debug ASP.NET MVC applications targeting the Chrome browser, one might encounter that both the IDE and browser hangs up. The workaround is to uncheck the Enable JavaScript debugging for ASP.NET (Chrome and IE) .

ASP.NET MVC Multiple PagedList Pager In A Single View

Image
Good afternoon! In a situation wherein a single page will contain multiple paging such as displaying master-details records or similar requirements, using a couple or more PagedList pager will cause logical errors such as when you click on the paging of details record to traverse to the next page, the paging of master record will move to the next record as well. In order to solve this dilemma, we need to assign a specific page variable to a PagedList object to prevent this issue from happening. In this example, I'll demonstrate showing products information from AdventureWorks database whose stocks are above or below a certain reorder point. The page model class below has two page properties namely BelowReorderPage and AboveReorderPage . And these properties are assigned to their specific PagedList object whether ProductsBelowReorder or ProductsAboveReorder . PageModel.cs public class PageModel { public int BelowReorderPage { get ; set ; } public int AboveReorderPage {

DataList In ASP.NET MVC With Paging Using PagedList And Bootstrap

Image
Here's an example ASP.NET MVC application that shows information in a DataList layout with pagination using PagedList Pager. The project also integrates Bootstrap for enhancing the UI and display the images from AdventureWorks Products table through an ImageHandler class. The significant files used in this project are: 1. PagingModel.cs/IndexModel.cs - These classes are responsible for defining the page number, size of page, and PagedList property that stores the information that are paged accordingly to it's size. public class PagingModel { public PagingModel () { Size = 24 ; Page = 1 ; } public int Page { get ; set ; } public int Size { get ; set ; } } public class IndexModel { public PagingModel PageModel { get ; set ; } public IndexModel (PagingModel pageModel) { Products = new PagedList<ProductViewModel>( new List<ProductViewModel>(), 1 , pageModel.Size); PageModel = pageModel; } public IPagedList<ProductViewModel>

HTTP Error 500.23 - Internal Server Error. An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode. (ASP.NET MVC HttpHandler)

Good day! I was trying to apply integrate an Image HttpHandler that discourages leeching from one of my Web Forms project to ASP.NET MVC. This hack is found on ASP.NET 2.0 MVP Hacks site. Upon running the ASP.NET MVC project, an issue was thrown to the browser specifically "HTTP Error 500.23 - Internal Server Error. An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode." Upon investigating, I found out that handlers in WebForms are declared in <httpHandlers> under <system.web>. <system.web> <httpHandlers> <add verb= "*" path= "*.jpg" type= "Events.Web.Extensions.NoLeechImageHandler" /> <add verb= "*" path= "*.jpeg" type= "Events.Web.Extensions.NoLeechImageHandler" /> <add verb= "*" path= "*.gif" type= "Events.Web.Extensions.NoLeechImageHandler" /> <add verb= "*" path=

Display Images Using Generic Handler In ASP.NET MVC

Image
There are several options on how to show images in ASP.NET MVC. One of them is using a generic handler. This method was applied since the early days of ASP.NET Webforms and still can be used with recent frameworks. The class below will render the images on the page by calling the ProcessRequest method which will then get the image from datasources such as database and file system and return it as a Bitmap object. public class ImageHandler : IHttpHandler { private OnlineShoppingDBEntities shoppingContext; public ImageHandler () { shoppingContext = new OnlineShoppingDBEntities(); } public void ProcessRequest (HttpContext context) { if (context.Request.QueryString[ "ProductID" ] != null ) { Product product = shoppingContext.Products.Find(Convert.ToInt32(context.Request.QueryString[ "ProductID" ])); if (product != null ) { Byte[] bytes = product.Image; int height = 0 ; int width = 0 ; height = 100 ; width = 10

Donate