Category Archives: Xml

Xml

[RESOLVED]How can I customize the text in a view depending on a word?

I have a web application? And I wanna change a part of the text layout? I want to use colors and text styles.

How can I customize the content of the text, that is loaded from an xml-file?

This a part of my xml-file:

...
<references>
    <![CDATA[
      using System;
      using System.ComponentModel;
    ]]>
</references>
...

… and this is a part of my view who had to represent the text with own created layout.

  <p>
            <span class="label">@Html.DisplayNameFor(model => model.Methods)</span>
            @{ 
                foreach (var method in item.Methods)
                {
                    <span>@Html.DisplayFor(modelItem => method)</span>
                }
            }
        </p>

The desired result:

References 
using System;
using System.ComponentModel;

the common approach is write a javascript parser that parses the text into a node tree, and then produce a html fragment based on that tree. see any of the javascript based code syntax highlighters. for example:

   http://alexgorbatchev.com/SyntaxHighlighter/

Such like this??

<script type="text/javascript">
$(document).ready(function () {
changeContent();
});

function changeContent() {
$(".sourcecode").replaceAll("using", "<b>using</b>");
}

</script>

wesley.hs76

Such like this??

Sure! If you had one or more "sourcecode" areas, you could create a specific style for certain elements you wanted to replace and then use something like this to handle your replacement :

<!-- jQuery Reference -->
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script type='text/javascript'>
    // When your page loads
    $(function(){
         // Clean up your source
         CleanSource();
    });  
  
    function CleanSource(){
        // Get the text of your sourcecode element(s) and clean them up
        $('.sourcecode').each(function(){
           $(this).html($(this).text().replace(/using/g,'<b>using</b>'));
        });
    }
</script>
<!-- Example Style -->
<style type='text/css'>
   /* Example style */
   .sourcecode b { color: blue; }  
</style>
</head>
<body>
    <!-- Example of Rendered Source -->
    <pre class='sourcecode'>
        using System;
        using System.ComponentModel;
    </pre>
</body>

You can see an example of this here or as seen rendered below :

This is exactly what I mean. Thank you. It works.

New MVC Project throws Compiler Error when run

I’m using Visual Studio 2013 and I create a new empty MVC project (with the MVC extensions ticked) in either VB or C#. I add a single Controller and a View for the Index method of the controller. When I run the project in IE I get the following page:

Server Error in ‘/’ Application.


Compilation Error

            
Description:
An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.            

Compiler Error Message: BC30451: ‘ViewData’ is not declared. It may be inaccessible due to its protection level.

Source Error:

Line 1:  @Code
Line 2:      ViewData("Title") = "Index"
Line 3:  End Code

What do I need to do to get the simplest of projects working ‘out of the box’? I’m assuming that there’s something wrong with either the templates used to generate the project or that Visual Studio 2013 is failing somewhere else when creating it.

The Views web.config appears to be good as it has all the namespace references:

<?xml version="1.0"?>
 
<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>
 
  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="MVCAjaxWorkbench" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
 
  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>
 
  <system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

The main web.config also appears to be correct:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

The code is not showing any errors at design time so why is a compiler error thrown at runtime?

Hi,

It seems that there are something error in the VS. You could share the project on the OneDrive, we will check whether it works fine.

You could repair your VS and try again.

Best Regards

Starain

[RESOLVED]I can't add a view after migrating my MVC4 project to MVC5

I migrated my MVC 4 project to MVC 5. I followed all the instructions on asp.net site from the article written by Rick Anderson. After removing GUId, I noticed that I can not add a view in my project again. Please how do I solve this problem. Currently I
would pasted the GUIDs that I have in my project so you can see and let me know if I deleted the wrong thing.

 <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

Error message displayed when I try to add a controller through scaffolding

There was an error running the selected code generator:
The parameter searchFolders does not contain any entries. Provide at least one folder to search files.
Parameter name: searchFolders’

Hi,

Yes, you are right. We should delete the MVC 4 project GUID and add the
<
projecttypeguids>.

And about the error, it seems to miss parameter for action method. Please add breakpoint to debug it.

https://www.asp.net/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

I removed the MVC4 Guid. Please help look that the segment of my config file that I pasted above am I missing something. I followed the steps in the link. Am even tired of looking at that link. Please if you have a template of how mvc5  <projecttypeguids>.
should look like kindly paste it.

Hi,

It is my section in .csproj file, please refer to the projectTypeGuids node:

<ProjectGuid>{D6931D20-BA0E-414D-BB48-CC1AA2605B59}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

[RESOLVED]Upgrade from MVC2-3

Hi
I am trying to upgrade my app from MVC 2 ->3, either using tools, or manual. However, when I tried to run my app, I hit error as below. Before upgrade, it is working fine.

The error pointed to ASPX inline code Url.Content(). Any ideas? tq

Edited: After some investigation, found that Url object is null. What cause this happen?

System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=App_Web_1r5z2fif
StackTrace:
at ASP.views_home_logon_aspx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:WorksMyApp V26.0CodeMyAppWebViewsHomeLogOn.aspx:line 10
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
at System.Web.UI.Page.Render(HtmlTextWriter writer)
at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:

Are you getting this error in the MVC3 or MVC2.

pprasannak

Are you getting this error in the MVC3 or MVC2.

MVC3. working fine in MVC2

Edited: Found that MVC2 hit the same exception now after I installed MVC3. I didnt change anything to MVC2 project. =.=

Hi chanmy8,

Thanks for your post.

According to your description,

chanmy8

Upgrade from MVC2-3

ASP.NET MVC 3 can be installed side by side with ASP.NET MVC 2 on the same computer, which gives you flexibility in choosing when to upgrade an ASP.NET MVC 2 application to ASP.NET MVC 3.

To manually upgrade an existing ASP.NET MVC 2 application to version 3, do the following:

  1. Create a new empty ASP.NET MVC 3 project on your computer. This project will contain some files that are required for the upgrade.
  2. Copy the following files from the ASP.NET MVC 3 project into the corresponding location of your ASP.NET MVC 2 project. You’ll need to update any references to the jQuery library to account for the new filename ( jQuery-1.5.1.js): 
    • /Views/Web.config
    • /packages.config
    • /scripts/*.js
    • /Content/themes/*.*
  3. Copy the packages folder in the root of the empty ASP.NET MVC 3 project solution into the root of your solution, which is in the directory where the solution’s .sln file is located.
  4. If your ASP.NET MVC 2 project contains any areas, copy the /Views/Web.config file to the
    Views folder of each area.
  5. In both Web.config files in the ASP.NET MVC 2 project, globally search and replace the ASP.NET MVC version. Find the following:
    System.Web.Mvc, Version=2.0.0.0

    Replace it with the following:

    System.Web.Mvc, Version=3.0.0.0
  6. In Solution Explorer, delete the reference to System.Web.Mvc (which points to the DLL from version 2), then add a reference to
    System.Web.Mvc (v3.0.0.0).
  7. Add a reference to System.Web.WebPages.dll and System.Web.Helpers.dll. These assemblies are located in the following folders: 
    • %ProgramFiles% Microsoft ASP.NETASP.NET MVC 3Assemblies
    • %ProgramFiles% Microsoft ASP.NETASP.NET Web Pagesv1.0Assemblies
  8. In Solution Explorer, right-click the project name and select Unload Project. Then right-click the project name again and select Edit
    ProjectName.csproj.
  9. Locate the ProjectTypeGuids element and replace {F85E285D-A4E0-4152-9332-AB1D724D3325} with {E53F8FEA-EAE0-44A6-8774-FFD645390401}.
  10. Save the changes, right-click the project, and then select Reload Project.
  11. In the application’s root Web.config file, add the following settings to the
    assemblies
    section.

    <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, 
         PublicKeyToken=31BF3856AD364E35" />
    
    <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral,
         PublicKeyToken=31BF3856AD364E35" />
  12. If the project references any third-party libraries that are compiled using ASP.NET MVC 2, add the following highlighted
    bindingRedirect element to the Web.config file in the application root under the
    configuration section:

    <runtime>
       <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly>
           <assemblyIdentity name="System.Web.Mvc"
               publicKeyToken="31bf3856ad364e35"/>
           <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0"/>
         </dependentAssembly>
       </assemblyBinding>
    </runtime>

More information,you can refer to the following link:

#Upgrading an ASP.NET MVC 2 Project to ASP.NET MVC 3 Tools Update

http://www.asp.net/whitepapers/mvc3-release-notes#upgrading

Hope this can be helpful.

Best Regards,

Eileen

[RESOLVED]How to bind dynamically the Columnnames,Column values,and Data in jqgrid?

public JsonResult GridRecords1()
{ 
//var records = objInstituteRegistrationBusiness.GridRecords();
////return Json(records, JsonRequestBehavior.AllowGet); 
//dynamic obj;
//obj = objInstituteRegistrationBusiness.GridRecords();
//DataTable dt = GetDataTableFromObjects(obj);

//var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//string jsonString = javaScriptSerializer.Serialize(records);
//return Json(jsonString, JsonRequestBehavior.AllowGet);
var result = new
{
Json = new
{
colNames = new[]
{
"institutionid","institutionname", "displayname", "shortname","supportedfield","schemename","subscriptionto"
},

colModels = new[]
{ 
new { name= "institutionid", hidden= false, sortable= true, sorttype= "int", formatter= string.Empty, formatoptions = string.Empty },
new { name= "institutionname", hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "displayname", hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "shortname" ,hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "supportedfield",hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "schemename", hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "subscriptionto", hidden= false, sortable= true, sorttype= "string", formatter= "date", formatoptions = "dd/mm/YYYY" }

},
data = new
{
options = new
{
page = "1",
total = "1",
records = "1",
rows = new[] {
new{institutionid=1,institutionname="test",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="20/11/2014" },
new{institutionid=12,institutionname="test2",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/03/2014" },
new{institutionid=11,institutionname="test3",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/11/2014" },
new{institutionid=10,institutionname="test4",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/11/2014" },
new{institutionid=9,institutionname="test5",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/11/2014" },
new{institutionid=5,institutionname="test6",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/12/2014" },
new{institutionid=3,institutionname="test7",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/01/2014" }, 
}
}
}
}
};
//return Json(result);
return Json(result, JsonRequestBehavior.AllowGet);
}



[Authorize]
public ActionResult GridViewInstituteDynamicBinding()
{
return View();
}



View:

<script src="../Scripts/jqGrid/i18n/grid.locale-en.js"></script>


<table id="list2">

</table>

<div id="pager2"></div>

<table id="grid-table"></table>

<div id="grid-pager"></div>


<script type="text/javascript">
$.extend(
$.jgrid.search,
{
closeOnEscape: true,
closeAfterSearch: true,
//closeAfterReset:true,
overlay: 0,
Reset: "Reset",
Find: "Find"
}
);

var recordids = new Array();

jQuery(function ($) {
var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";

//resize to fit page size
$(window).on('resize.jqGrid', function () {
$(grid_selector).jqGrid('setGridWidth', $(".page-content").width());
})
//resize on sidebar collapse/expand
var parent_column = $(grid_selector).closest('[class*="col-"]');
$(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
//setTimeout is for webkit only to give time for DOM changes and then redraw!!!
setTimeout(function () {
$(grid_selector).jqGrid('setGridWidth', parent_column.width());
}, 0);
}
})


var selaArrr = [];

jQuery(grid_selector).jqGrid({
//direction: "rtl",

//subgrid options
subGrid: false,
//subGridModel: [{ name : ['No','Item Name','Qty'], width : [55,200,80] }],
//datatype: "xml",
subGridOptions: {
plusicon: "ace-icon fa fa-plus center bigger-110 blue",
minusicon: "ace-icon fa fa-minus center bigger-110 blue",
openicon: "ace-icon fa fa-chevron-right center orange"
},
///veera

multiselect: true, 
onSelectRow: function (id, status, e)
{

},
onSelectAll: function (aRowids, status,id,e)
{
recordids = [];

if (status)
{
//$('#add_grid-table').hide();
//$('#edit_grid-table').hide();
}
else {
//$('#add_grid-table').show();
//$('#edit_grid-table').show();
}
for (var i = 0; i < aRowids.length; i++)
{
var myGrid = $('#grid-table'),
// selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'),
cellValue = myGrid.jqGrid('getCell', aRowids[i], 'institutionid');
recordids.push(cellValue);
}


},
ondblClickRow: function (rowid, iRow, iCol, e)
{
var myGrid = $('#grid-table'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'),
cellValue = myGrid.jqGrid('getCell', rowid, 'institutionid');
window.location = "../Ace/EditRecord?rowid=" + cellValue + "&operation=ViewRecord";
},

//for this example we are using local data
subGridRowExpanded: function (subgridDivId, rowId) {
var subgridTableId = subgridDivId + "_t";
$("#" + subgridDivId).html("<table id='" + subgridTableId + "'></table>");
$("#" + subgridTableId).jqGrid({
datatype: 'json',
data: subgrid_data,
colNames: ['ID', 'Institution Name', 'Short Name', 'Board of Education', 'Website Address'],
colModel: [
{ name: 'id', width: 50 },
{ name: 'name', width: 150 },
{ name: 'qty', width: 50 }
]
});
},



url: "../Ace/GridRecords1",
datatype: "json",
height: 250, 

//Here i need to bind the Controller Data,Column model,Column names dynamically But now i have to give colNames: ['ID', 'Institution Name', 'Display Name', 'Short Name', 'Board of Education', 'Scheme Name','Subscription Date'], colModel: [ { name: 'institutionid', hidden: true, sortable: true, sorttype: "int" }, { name: 'institutionname', sortable: true }, { name: 'displayname', sortable: true }, { name: 'shortname' ,sortable: true}, { name: 'supportedfield', sortable: true }, { name: 'schemename', sortable: true }, { name: 'subscriptionto', hidden: true, sortable: true, formatter: "date", formatoptions: { newformat: "d/m/Y" } } ], viewrecords: true, rowNum: 10, height: '350px', loadtext: "Processing pending request data please wait...", rowList: [10, 20, 30], idsOfSelectedRows: [], pager: pager_selector, reloadAfterSubmit:true, altRows: true, sortorder: "ASC", loadonce: true, //toppager: true, multiselect: true, scrollerbar:true, //multikey: "ctrlKey", multiboxonly: true, afterSubmit: function () { $(grid_selector).jqGrid().setGridParam( { datatype: "json", page: 1, url: "GridRecords", } ).trigger("reloadGrid"); }, onSelectRow: function (id, isSelected,status) { var p = this.p, idsOfSelectedRows = p.idsOfSelectedRows, item = p.data[p._index[id]], i = $.inArray(id, idsOfSelectedRows); item.cb = isSelected; if (!isSelected && i >= 0) { idsOfSelectedRows.splice(i, 1); // remove id from the list recordids.splice(i, 1); // remove id from the list if (recordids.length == 1 || recordids.length == 0) { //$('#edit_grid-table').show(); } else { //$('#edit_grid-table').hide(); } if (recordids.length == 0) { //$('#add_grid-table').show(); } else { //$('#add_grid-table').hide(); } } else if (i < 0) { idsOfSelectedRows.push(id); var myGrid = $('#grid-table'), selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'), cellValue = myGrid.jqGrid('getCell', id, 'institutionid'); recordids.push(cellValue); if (recordids.length == 1 || recordids.length == 0) { //$('#edit_grid-table').show(); } else { //$('#edit_grid-table').hide(); } if (recordids.length == 0) { //$('#add_grid-table').show(); } else { //$('#add_grid-table').hide(); } } }, loadComplete: function () { var table = this; setTimeout(function () { styleCheckbox(table); updateActionIcons(table); updatePagerIcons(table); enableTooltips(table); }, 0); }, //editurl: "DeleteRecord",//nothing is saved caption: "Registered Institutes" }); $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size function aceSwitch(cellvalue, options, cell) { setTimeout(function () { $(cell).find('input[type=checkbox]') .addClass('ace ace-switch ace-switch-5') .after('<span class="lbl"></span>'); }, 0); } //enable datepicker function pickDate(cellvalue, options, cell) { setTimeout(function () { $(cell).find('input[type=text]') .datepicker({ format: 'dd/MM/yyyy', autoclose: true }); }, 0); } //navButtons jQuery(grid_selector).jqGrid('navGrid', pager_selector, { //navbar options edit: true, editicon: 'ace-icon fa fa-pencil blue', add: true, addicon: 'ace-icon fa fa-plus-circle purple', del: true, delicon: 'ace-icon fa fa-trash-o red', search: true, searchicon: 'ace-icon fa fa-search orange', refresh: true, refreshicon: 'ace-icon fa fa-refresh green', view: true, viewicon: 'ace-icon fa fa-search-plus grey', view: true, edit: true, add: true, del: true, view: true, editfunc: function () { var myGrid = $('#grid-table'), selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'), cellValue = myGrid.jqGrid('getCell', selectedRowId, 'institutionid'); window.location = "../Ace/EditRecord?rowid=" + cellValue + "&operation=EditRecord"; }, addfunc: function () { var myGrid = $('#grid-table'), selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'), cellValue = myGrid.jqGrid('getCell', selectedRowId, 'institutionid'); // Add(); window.location = "../Ace/Aceadmin?operation=Addrecord"; }, delfunc: function (id, status, e) { $.alert.open({ type: 'confirm', content: 'Do you want to delete the selected Institute?', callback: function (button) { if (button == 'yes') { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", data: "{'recordid':'" + recordids + "'}", url: "../Ace/DeleteRecord", dataType: "html", success: function (data) { var msg = jQuery.parseJSON(data); $('.deletealert').html('<button type="button" class="close" data-dismiss="alert">'+'<i class="ace-icon fa fa-times"></i>'+ '</button>'+'<b>Success!</b>' + " " + msg.Message); $('.deletealert').css("display", "block"); window.setTimeout(function () { $('.deletealert').css("display", "none"); }, 5000); $('#edit_grid-table').show(); $('#add_grid-table').show(); $(grid_selector).jqGrid().setGridParam( { datatype: "json", page: 1, url: "GridRecords", } ).trigger("reloadGrid"); recordids.splice(0, recordids.length); }, error: function (xhr, ajaxOptions, thrownError) { //alert(thrownError); $.alert.open({ title: 'Warning', type: 'warning', content: thrownError }); } }); } } }); }, viewfunc: function () { var myGrid = $('#grid-table'), selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'), cellValue = myGrid.jqGrid('getCell', selectedRowId, 'institutionid'); window.location = "../Ace/EditRecord?rowid=" + cellValue + "&operation=ViewRecord"; } }, { recreateForm: false, }, { closeAfterAdd: true, recreateForm: true, viewPagerButtons: false, beforeShowForm: function (e) { var form = $(e[0]); form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar') .wrapInner('<div class="widget-header" />') style_edit_form(form); } }, { //delete record form recreateForm: true, beforeShowForm: function (e) { var form = $(e[0]); if (form.data('styled')) return false; form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />') style_delete_form(form); form.data('styled', true); }, onClick: function (e) { alert(1); } }, { //search form recreateForm: true, afterShowSearch: function (e) { var form = $(e[0]); form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />') style_search_form(form); </script>

Instead of posting the entire code, please point out the code you are having problem.

Hi,

For this requirement, please refer to this links below:

# Jqgrid with dynamic colNames?

http://stackoverflow.com/questions/13452132/jqgrid-with-dynamic-colnames

# Dynamic column genrate jqgrid in asp.net mvc razor

http://feel-tech-evolution.blogspot.jp/2013/07/dynamic-column-genrate-jqgrid-in-aspnet.html

Best Regards

Starain

[RESOLVED]menu when button hover

Hi

I have a share image button in my website and what i looking for is when user move the mouse on the image a small menu appear, can any one help me with it or refer me to a good online tutorial 

Many thanks 

Hi,

Take a look at this video:

https://www.youtube.com/watch?v=lx0IysyYLH0,

Have fun

Hi msimo.

For your issue,i wrote a demo for you:

When mouse on the image,it will show the menu,when mouse leave the image,it will hide the menu.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#test").mouseenter(function () {
               $("#menu").show();
            
            })
            $("#test").mouseleave(function () {
                $("#menu").hide();

            })
           
        })
    </script>
</head>
<body>
    <ul>
        <li>   
            <img src="xx" id="test" />
            <ul id="menu" style="display:none">
                <li>A</li>
                <li>B</li>
                <li>C</li>
            </ul>
        </li>
    </ul>
    
</body>
</html>

Best Regards,

Kevin Shen.

[RESOLVED]Client-Side File Size Check

I am using .NET 4.0, 4.5, VB.NET, and the asp:FileUpload functionality to upload a file from the client’s PC to my web server. Prior to actually doing the upload I need to verify that the file size is less than some limit that I set (Ex: 10240 KB).

I know that I can limit the file size in the web.config using the maxRequestLength parameter. However, if I set this parameter to 10240 and the client uploads a file larger than that, the application blows up with a very unfriendly message. I could set the
maxRequestLength to something greater than 10240 KB and then check the file size after it has been uploaded to see if it is less than 10240 KB, however there is still the possibility the client will submit a file larger than the maxRequestLength.

I need to check the file size from the client side prior to the upload, give the client a friendly message if the size is greater than whatever I want the maximum to be, and then prevent the upload from occurring.

Does anyone know how to do this?

 

=

Here is my JSfor this, using simple javascript you can check file size.  JSFiddle- http://jsfiddle.net/c6pz1huz/1/

<input type="file" id="fl"/>
<input type="button" value="check file size" onclick="Checksize();" />



function Checksize()
{
var k = document.getElementById("fl").files[0].size;
alert( "file size in KB " + k/1024 );
}

using jquery:

var fileSize = $('#your_upload_control').get(0).files[0].size;

This gets you the size in bytes, here’s a helper for formatting to your users:

//Method to format a files bytes
    function formatBytes(num) {

        if (num <= 1023) {
            return num + " bytes";
        }
        else if (num >= 1024 && num <= 1048575) {
            return Math.round(num / 1024) + " kb";
        }
        else {
            return Math.round(num / 1048576) + " mb"
        }

    }//end of formatBytes()

arindamnayak,

Maybe it is my limited knowledge of ASP.NET and VB.NET, but your solution does not seem to incorporate the use of the asp:FileUpload functionality. I am not certain how to implement your solution and the asp:FileUpload into a single solution.  

remojr76,

I have the same problem with your solution. How do I combine your solution with the asp:FileUpload?

I was saying that, you can use ID field of asp:fileupload in JS too!. I.e. following will work, i mean it is.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function checkfile()
        {
            var k = document.getElementById("fl").files[0].size;
            alert("file size in KB " + k / 1024);
            return false;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fl" runat="server" />
        <asp:Button ID="btncheck" runat="server" OnClientClick="return checkfile();" Text="Check" />
   </div>
    </form>
</body>
</html>

The asp:FileUpload functionality automatically generates a field (textbox for lack of a better term) and a Browse button. When you click on the Browse button you get a window which allows the user to locate (browse to) the file to be uploaded. When they
highlight that file and click "Open", the window closes and the file they specified is displayed in the field (textbox). It is at this moment that I need the client (in the code behind) to get the file size for the file, test it, and generate a message if
it is greater than whatever maximum I specify.

The asp:FileUpload does not have an OnChange event that would allow me to execute client side code to check the file size.

The code you sent me creates a separate button which the user must click or I have to find some way of executing the code behind automatically. I don’t want to rely on the user to click on this button. The Upload button (see the btnUpLoad_Click code behind
that is below) runs on the server and therefore cannot do the file size check until after the file has already been uploaded. 

 I do not understand exactly when the upload (file transfer from the client to the server) is performed. Does it happen upon completion of the Browse functionality when the file name is placed in the field (textbox) or does it happen when the FileUpload.SaveAsFile
statement (in the code below) is executed on the server? The following code is the OnClick event tied to an asp:Button which follows the asp:FileUpload.

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        'This sub comes from //www.dotnetbull.com/2013/03/how-to-upload-file-in-aspnet-using.html
        Debug.Print(Now() & " " & "FileUpload/FileUploadId.aspx, btnUpload_Click")

        Dim strFileSavePath As String
        Dim fileName As String = FileUpload.PostedFile.FileName
        Debug.Print(Now() & " " & "fileName=" & fileName)

        Dim fileExtension As String = System.IO.Path.GetExtension(fileName)
        Debug.Print(Now() & " " & "fileExtension=" & fileExtension & "|")

        Dim fileMimeType As String = FileUpload.PostedFile.ContentType
        Debug.Print(Now() & " " & "fileMimeType=" & fileMimeType & "|")

        Dim intfileLengthInKB As Integer = Math.Ceiling(FileUpload.PostedFile.ContentLength / 1024)
        Dim intfileLengthInMB As Integer = Math.Ceiling(intfileLengthInKB / 1024)
        Debug.Print(Now() & " " & "fileLengthInKB=" & intfileLengthInKB)

        Dim maxintfileLengthInKB As Integer = 10240    'max filesize = 10MB = 10240KB 
        Dim maxintfileLengthinMB As Integer = maxintfileLengthInKB / 1024
        Debug.Print(Now() & " " & "maxintfileLengthInKB=" & maxintfileLengthInKB)

        'The matchExtension and matchMimeType values come from 
        ' //www.telerik.com/help/aspnet-ajax/upload-mime-types.html
        Dim matchExtension As String = ".xls .xlsx"

        Dim matchMimeType As String = "application/excel application/vnd.ms-excel application/x-excel application/x-msexcel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

        If FileUpload.HasFile Then
            Debug.Print(Now() & " " & "HERE 1")
            Debug.Print(Now() & " " & "matchExtension.Contains(fileExtension)=" & matchExtension.Contains(fileExtension))
            Debug.Print(Now() & " " & "matchExtension.Contains(fileMimeType)=" & matchExtension.Contains(fileMimeType))
            If matchExtension.Contains(fileExtension) And matchMimeType.Contains(fileMimeType) Then
                Debug.Print(Now() & " " & "HERE 2")
                If intfileLengthInKB <= maxintfileLengthInKB Then
                    Debug.Print(Now() & " " & "HERE 3")
                    Try

                        Debug.Print(Now() & " " & "HERE 4")
                        If Me.Session("ProdTestServer") = "Prod" Then
                            strFileSavePath = "\CHEROKEE"
                        Else
                            strFileSavePath = "\dakotaishardingUploadedFiles"        'FOR TESTING
                            'strFileSavePath = "c:appsOnlineAgentData"        'FOR TESTING
                        End If
                        Debug.Print(Now() & " " & "strFileSavePath=" & strFileSavePath)

                        Dim strFileNameAtHCAD = "OAS_P_" & Session("gstr_v_Agent") & "_" & _
                                          DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") & "_" & _
                                          FileUpload.FileName
                        Dim strSaveAsFile = strFileSavePath & strFileNameAtHCAD
                        Debug.Print(Now() & " " & "FileUpload.SaveAs=" & strSaveAsFile)

                        FileUpload.SaveAs(strSaveAsFile)
                        lbl_FileUploadMsg11.Text = "File Name: "
                        lbl_FileUploadMsg12.Text = FileUpload.PostedFile.FileName
                        lbl_FileUploadMsg21.Text = "File Size: "
                        lbl_FileUploadMsg22.Text = intfileLengthInKB & " kb"
                        lbl_FileUploadMsg31.Text = "File Extension: "
                        lbl_FileUploadMsg32.Text = fileExtension
                        lbl_FileUploadMsg41.Text = "Mime Type: "
                        lbl_FileUploadMsg42.Text = FileUpload.PostedFile.ContentType
                        lbl_FileUploadMsg51.Text = "HCAD Filename Is: "
                        lbl_FileUploadMsg52.Text = strFileNameAtHCAD
                    Catch ex As Exception
                        lbl_FileUploadMsg11.Text = "ERROR:"
                        lbl_FileUploadMsg12.Text = ex.Message.ToString()
                        lbl_FileUploadMsg21.Text = ""
                        lbl_FileUploadMsg22.Text = ""
                        lbl_FileUploadMsg31.Text = ""
                        lbl_FileUploadMsg32.Text = ""
                        lbl_FileUploadMsg41.Text = ""
                        lbl_FileUploadMsg42.Text = ""
                        lbl_FileUploadMsg51.Text = ""
                        lbl_FileUploadMsg52.Text = ""
                    End Try
                    Response.Write("File Uploaded Successfully")
                Else
                    lbl_FileUploadMsg11.Text = "ERROR: "
                    lbl_FileUploadMsg12.Text = "Maximum upload file size is " & maxintfileLengthInKB & " KB (" & maxintfileLengthinMB & " MB). Your file size is " & intfileLengthInKB & " KB (" & intfileLengthInMB & " MB)."
                    lbl_FileUploadMsg21.Text = ""
                    lbl_FileUploadMsg22.Text = ""
                    lbl_FileUploadMsg31.Text = ""
                    lbl_FileUploadMsg32.Text = ""
                    lbl_FileUploadMsg41.Text = ""
                    lbl_FileUploadMsg42.Text = ""
                    lbl_FileUploadMsg51.Text = ""
                    lbl_FileUploadMsg52.Text = ""
                End If
            Else
                lbl_FileUploadMsg11.Text = "Informational: "
                lbl_FileUploadMsg12.Text = "Please select only .xls or .xlsx files."
                lbl_FileUploadMsg21.Text = ""
                lbl_FileUploadMsg22.Text = ""
                lbl_FileUploadMsg31.Text = ""
                lbl_FileUploadMsg32.Text = ""
                lbl_FileUploadMsg41.Text = ""
                lbl_FileUploadMsg42.Text = ""
                lbl_FileUploadMsg51.Text = ""
                lbl_FileUploadMsg52.Text = ""
            End If
        Else
            lbl_FileUploadMsg11.Text = "Informational: "
            lbl_FileUploadMsg12.Text = "You have not specified a file."
            lbl_FileUploadMsg21.Text = ""
            lbl_FileUploadMsg22.Text = ""
            lbl_FileUploadMsg31.Text = ""
            lbl_FileUploadMsg32.Text = ""
            lbl_FileUploadMsg41.Text = ""
            lbl_FileUploadMsg42.Text = ""
            lbl_FileUploadMsg51.Text = ""
            lbl_FileUploadMsg52.Text = ""
        End If

    End Sub

 

I just tested this and it works:

<div>

        <asp:FileUpload ID="myUpload" ClientIDMode="Static" runat="server" />
    
    </div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script>

        $(function () {

            $('#myUpload').change(function () {

                alert($(this).get(0).files[0].size);

            });

        });
        

    </script>

Hope it helps!

I have tried the following without success:

                var filesize = $(this).get(0).files[0].size;
                var filesize = $('#MainContent_FileUpload').get(0).files[0].size;

When I use either one of the above lines of code I get the following message:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

Using the $(‘#MainContent_FileUpload’).val() is am able to get the name of the file to be uploaded.

Below is the jscript code I am using, along with various lines of code that attempt to get the file size. None of them work. The code that gets fileName does work.

    <script type="text/jscript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script type="text/jscript">

        $(function () {
            //alert("I AM HERE 1 !!");
            $('#MainContent_FileUpload').change(function () {
                alert("I AM HERE 2 !!");

                var objFileUpload = $('#MainContent_FileUpload')
//                var fileName = $('#MainContent_FileUpload').val();
                var fileName = objFileUpload.val();
                alert('fileName : ' + fileName);

//                var fileSize = $('#MainContent_FileUpload').size.val();
//                var fileSize = $('#MainContent_FileUpload').files[0].size;
//                var fileSize = $('#MainContent_FileUpload').files[1].size();
//                var filesize = $('#MainContent_FileUpload').files.size;
//                var fileSize = this.files[0].size;
//                var filesize = this.files.size;
//                var fileSize = document.files[0].size;
//                var filesize = document.files.size;
//                var fileSize = objFileUpload.files[1].size();
//                var filesize = $(this).get(0).files[0].size;
                var filesize = $('#MainContent_FileUpload').get(0).files[0].size;
                alert('fileSize : ' + fileSize);

//                var fileSize = $('#MainContent_FileUpload').files[0].size;
//                var fileType = $('#MainContent_FileUpload').files[0].type;
//                alert('FileName : ' + fileName + 'nFileSize : ' + fileSize + ' bytes');
//                //alert($(this).get(0).files[0].size);

            });

        });
    </script>

Does anyone have any other suggestions?

What is the name of your File Upload control? Best not to name if FileUpload since that’s already the name of the class. When referencing a control, you need to get it’s client id property. ASP.Net will generate a unique id for each control based on it’s
position in the control tree.

Try:

$('#<%= ControlName.ClientID %>')

This is a tricky control to work with client-side. The FIleUpload control actually isn’t rendering a field and a button, all it does is emit a file input control. <input type="file" > That’s all it does on that side really. It does a lot more though on the
server side to help you deal with the upload. The browsers and W3C keep the file input element sparse as far as what you can do with it to avoid it from becoming a security issue. Example: what would happen if you could set the filename, then you could swap
the user selected file for another more sensitive filename without them knowing. That’s one of the reasons it’s fairly tricky. Also, a lot of the features for doing things such as determining file size only work in newer browsers due to advances in HTML5.

markfitzme,

As you recommended I have renamed all references to my File Upload control to FileUploadToOAS.

I was not certain where to use the $("#… code you suggested so my first attempt was:

                var filesize = $('#<%= FileUploadToOAS.ClientID %>').get(0).files[0].size;
                alert('fileSize : ' + fileSize);

I am still getting the error message:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

on the "var filesize =…" statement.

Do you have any further suggestions?

Is the File upload control ClientIDMode set to Static?

  <asp:FileUpload ID="myUpload" ClientIDMode="Static" runat="server" />

 

remojr76,

Yes

<asp:FileUpload ID="FileUploadToOAS" Width="100%" ClientMode="Static" runat="server" />

you can use like this.

var filesize = $('#<%= FileUploadToOAS.ClientID %>').files[0].size;
                alert('fileSize : ' + fileSize);

arindamnayak,

Your suggestion did not work.

Please see my jscript below.

Note the runtime errors that were generated for each of the attempts at getting the file size occurred on the line of code indicated except for the "//JavaScript runtime error: ‘fileSize’ is undefined" error which occurred on the "alert(‘fileSize
: ‘
+ fileSize);" statement.

    <script type="text/jscript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script type="text/jscript">

        $(function () {
            //alert("I AM HERE 1 !!");
            $('#MainContent_FileUploadToOAS').change(function () {
//                alert("I AM HERE 2 !!");

                var objFileUploadToOAS = $('#MainContent_FileUploadToOAS')
//                var fileName = $('#MainContent_FileUploadToOAS').val();
                var fileName = objFileUploadToOAS.val();
//                alert('fileName : ' + fileName);

//                var fileSize = $('#MainContent_FileUploadToOAS').size.val();                  //JavaScript runtime error: Object doesn't support property or method 'val'
//                var fileSize = $('#MainContent_FileUploadToOAS').files[0].size;               //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var fileSize = $('#MainContent_FileUploadToOAS').files[1].size();             //JavaScript runtime error: Unable to get property '1' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').files.size;                  //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var filesize = MainContent_FileUploadToOAS.PostedFile.ContentLength;          //JavaScript runtime error: 'MainContent_FileUploadToOAS' is undefined
//                var filesize = objFileUploadToOAS.PostedFile.ContentLength;                   //JavaScript runtime error: Unable to get property 'ContentLength' of undefined or null reference
//                var fileSize = this.files[0].size;                                            //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = this.files.size;                                               //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var fileSize = document.files[0].size;                                        //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = document.files.size;                                           //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var fileSize = objFileUploadToOAS.files[1].size();                            //JavaScript runtime error: Unable to get property '1' of undefined or null reference
//                var filesize = $(this).get(0).files[0].size;                                  //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).files[0].size;        //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#<%= FileUploadToOAS.ClientID %>').get(0).files[0].size;    //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).size;                 //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').get(0);                      //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').size;                        //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').size();                      //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).size();               //JavaScript runtime error: Function expected
                var filesize = $('#<%= FileUploadToOAS.ClientID %>').files[0].size;             //JavaScript runtime error: Unable to get property '0' of undefined or null reference

                alert('fileSize : ' + fileSize);

//                var fileSize = $('#MainContent_FileUploadToOAS').files[0].size;
//                var fileType = $('#MainContent_FileUploadToOAS').files[0].type;
//                alert('FileName : ' + fileName + 'nFileSize : ' + fileSize + ' bytes');
//                //alert($(this).get(0).files[0].size);

            });

        });
    </script>

I have tried following , and it is working as expected. Note: your JS is wrong, as JS is case sensitive , if you have "var filesize " and later use "fileSize", it will not work, rather error will be shown.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <script type="text/javascript" >
        function onfilechange() {
            var fileSize = document.getElementById("<%= FileUploadToOAS.ClientID %>").files[0].size;
            alert('fileSize : ' + fileSize);
        }
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
    </div>
        <asp:FileUpload ID="FileUploadToOAS" runat="server" onchange="onfilechange();"/>
        
    </form>
</body>

</html>

arindamnayak,

Is the onfilechange function executed on the server or on the client?

If it is executed on the server that means that the file must be uploaded before the filesize can be checked. I want the filesize checked before the upload occurs so that the user is prevented from uploading a file larger than the maximum I have specified
in my web.config file.

Additionally:

When I tried your suggestion using the onchange attribute with the asp:FileUpLoad I get the following message:

Message 3 Validation (ASP.Net): Attribute ‘onchange’ is not a valid attribute of element ‘FileUpload’. C:Online Agent ServicesOASv2-2FileUploadFileUploadId.aspx 158 106 C:Online Agent ServicesOASv2-2

I tried running with the above error anyway and got the following message in the onfilechange function on the line where it is setting the var filesize =:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

I am still looking for a solution to the problem of client-side file size check. None of the suggestions above have worked.

Thanks.

All i can say is, it is working for me, and onchange is  JS attribute, that might not get detected by VS. So finally you are getting JS error.

If you put the code i had given in an ASPX and browse, check view source, you will get the following

<input
type
="file"
name
="FileUploadToOAS" id="FileUploadToOAS"
onchange="checkfile();" />

i.e. it translates to simple input type file, so it should work.

Can you do rightclick-view source and paste that specific HTML here.

arindamnayak,

The asp:FileUpload functionality generates an input type="file" as you indicated. However, it also generates a browse button which, when clicked, opens a window allowing the user to browse to the file on their network to be uploaded. The "onchange=" event
gets a "Validation (ASP.Net): Attribute ‘onchange’ is not a valid attribute of element ‘FileUpload’" message in the Error List.

Below is the code generated as seen in the "View Source":

                                <tr>
                                    <td colspan="1" align="right"  style="width:15%; padding-right:5px;">
                                        <span id="MainContent_Label15" style="display:inline-block;color:Black;width:100%;">File :</span>
                                    </td>
                                    <td colspan="1" align="left" style="width:85%; text-align:left; padding-top:0px;" >
                                        <input type="file" name="ctl00$MainContent$FileUploadToOAS" id="MainContent_FileUploadToOAS" onchange="CheckFileSize()" style="width:100%;" />
                                        
                                        
                                    </td>
                                </tr>

Below is the CheckFileSize function:

    <script type="text/javascript" >
        function CheckFileSize() {
            var fileSize = document.getElementById("MainContent_FileUploadToOAS").files[0].size;
            alert('CheckFileSize, fileSize : ' + fileSize);
        }
    </script>

It’s not really generating a button. The browser does that for an input type=file, not HTML or ASP.Net. ASP.Net won’t allow onchange because it’s not a supported property. You can add it in codebehind though like so:

if(!Page.IsPostBack)
{FileUploadToOAS.Attributes.Add("onchange","CheckFileSize()");}

Hi,

Have you tried the http://jsfiddle.net/c6pz1huz/1/ Fiddle posted earlier? Does it work with your browser?

What is the browser you are using to test suggestions which are made?

With the code you have give, it should work. Yes, VS might show warning  that, onchange is not valid, But JS work this way only. If that is not working, there can be some JS error , you are getting in browser, can you post those error, or  "CheckFileSize",
is not invoked at all?

[RESOLVED]Client side validation doesnt work

I am trying to validate a control on the client side and change the background of the control. Why is not working

Thank you

<td><asp:TextBox ID="txtName" runat="server" Width="100px"></asp:TextBox>
                            <asp:CustomValidator ID="CustomValidator1" runat="server" 
                                ErrorMessage="*" ValidateEmptyText="True" SetFocusOnError="True" ControlToValidate="txtName" 
                                ClientValidationFunction="inputValidation"></asp:CustomValidator>
                        </td>
<script type ="text/javascript" src="JavaScript/jquery-1.3.2.min.js">

    function inputValidation(source, args)
    {
        if(args.Value == "")
        {
            source.className = "errorControl";
        }
        else
        {
            source.className = "";
        }
    }


    </script>

Hi,

Try following

It seems that your logic in javascript function is not working. 

refer updated code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .errorControl {
            background-color: Red;
        }
    </style>
    <script type="text/javascript">
        function inputValidation(source, args) {
            if (args.Value == "") {
                document.getElementById(source.controltovalidate).className = 'errorControl';
            }
            else {
                document.getElementById(source.controltovalidate).className = '';
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtName" runat="server" Width="100px"></asp:TextBox>
            <asp:CustomValidator ID="CustomValidator1" runat="server"
                ErrorMessage="*" ValidateEmptyText="True" SetFocusOnError="True" ControlToValidate="txtName"
                ClientValidationFunction="inputValidation"></asp:CustomValidator>
        </div>
    </form>
</body>
</html>

Regards, Ajay

You need to find the reference of your control first using the source parameter like given below and then change the color of textbox as per your design.

<style>
        .errorControl
        {
            background-color: Red;
        }
    </style>
    <script type="text/javascript">

        function inputValidation(source, args) {
        //Get reference to your control here first
            var ctrl = document.getElementById(source.controltovalidate);
            if (args.Value == "") {
                //source.className = "errorControl";
                if (ctrl) {
                    ctrl.style.background = '#FFAAAA';
                }
            }
            else {
                if (ctrl) {
                    ctrl.style.backgroundColor = '';
                }
                //source.className = "";
            }
        }
    </script>
    <asp:TextBox ID="txtName" runat="server" Width="100px"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="*" ValidateEmptyText="True"
        SetFocusOnError="True" ControlToValidate="txtName" ClientValidationFunction="inputValidation"></asp:CustomValidator>