lundi 31 août 2015

string.Format vs String.Format in Razor

I have to output an employee's name and dept in the view like Welcome 'employee' to 'dept'. I am using string.Format(). I was playing around with String.Format and string.Format() and saw the following. Can someone please explain why string.Format() doesn't work or what am i missing in the code? I was reading online and saw that string.Format() and String.Format() give the same result.

Doesn't work-

<div>
  <div> Welcome </div>
    <div>
       @if(employee != null)
       {
           @string.Format("{0} at {1}", employee.name, emp.dept)
       }
    </div>
</div>

Error- Unexpected "string" keyword after "@" character. Once inside code, you do not need to prefix constructs like "string" with "@".

Works:

<div>
  <div> Welcome </div>
   <div>
     @if(employee != null)
     {
        @(string.Format("{0} to {1}", employee.name, emp.dept))
     }
   </div>
</div>

Works

<div>
   <div> Welcome </div>
     <div>
        @if(employee != null)
        {
            @String.Format("{0} at {1}", employee.name, emp.dept)
        }
   </div>
</div>

WebMarkupMin.Mvc referring higher version of Mvc

I'm using WebmarkupMin in some of my projects for some time now but when i started a new project today i had this problem with it's version and MVC version.

I'm using .NET MVC 3 and Visual Studio 2012, i already checked the version of WebMarkupMin on the website and it's ok, i downloaded it using NuGet, already tried to remove and add it again and nothing.

Assembly 'WebMarkupMin.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=99472178d266584b'
uses 'System.Web.Mvc, Version=3.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
which has a higher version than referenced assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' d:\Jobs em Andamento\Skill2015\packages\WebMarkupMin.Mvc.1.0.0\lib\net40\WebMarkupMin.Mvc.dll

My web.config also has a assembly binding that was there before i installed the WebMarkupMin:

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

I already tried to change the older version to 3.0.0.1 but i still get the same error.

How can i fix that ?

Is this scope and javascript oop approach is correct?

I am developing mvc project and I am writing jQuery functions very much per page and it's getting complex while function counts incresing. Finally page header looks very dirty.

I decided using java-script's oop, I wrote this code:

var thisPage = function () {
        var page = this;
        page.showLoader = function () { //show loader codes };
        page.hideLoader = function () { //hide loader codes };
        page.database = function () { };
        page.database.getSomethingFromDb = function (campaignId) {
            //Get some data from db
        };
        page.database.getSomethingFromDb2 = function (campaignID) {
             //Get some data from db
        };
        page.database.getSomethingFromDb3 = function (campaignID) {
             //Get some data from db
        };
        page.multiselects = function () 
        { 
          this.multiselects.campaigns(); 
          this.multiselects.teams(); 
        };
        page.multiselects.campaigns = function () {
            //Kampanya listesi
            $("#campaigns-list").on("change", function () {
                page.database.getTeamsByCampaignId(selectedCampaignId);
                page.database.getProductsByCampaignId(selectedCampaignId);
            });
        };
        page.multiselects.teams = function () {
            $("#team-list").on("change", function () {
                page.database.getUsersByTeamId(selectedTeamId);
            });

        };
        ///... some more functions which seperated by subclass in thisPage class
    };
    $(document).ready(function () {
      //Get new instance from thisPage class
        var page = new thisPage();

        //Bind multiselects
        page.multiselects();

        //Maybe I could call some another thisPage class's functions...

    });

I thought this approach keep my code readable and editable.

What do you guys think on this kind of approach ?

Should I keep it ?

cannot be called with instance of type 'System.Data.Entity.Core.Objects.ObjectQuery

I want to Find Username by userId

this code snippet working

Discussion_CreateBy = db.AspNetUsers.Find(discussion.CreatedBy).UserName,

and this once not working in following controller class

Comment_CreateBy = db.AspNetUsers.Find(c.CreatedBy).UserName,

this is my model classes

public class DiscussionVM
{
    public int Disussion_ID { get; set; }
    public string Discussion_Title { get; set; }
    public string Discussion_Description { get; set; }
    public Nullable<System.DateTime> Discussion_CreateDate { get; set; }
    public string Discussion_CreateBy { get; set; }

    public string Comment_User { get; set; }

    public IEnumerable<CommentVM> Comments { get; set; }

}

public class CommentVM
{

    public int Comment_ID { get; set; }
    public Nullable<System.DateTime> Comment_CreateDate { get; set; }
    public string Comment_CreateBy { get; set; }
    public string Comment_Description { get; set; }

}

this is whole controller class

    public ActionResult Discussion_Preview()
    {
        int Discussion_ID = 1;

        var discussion = db.AB_Discussion.Where(d => d.Discussion_ID == Discussion_ID).FirstOrDefault();
        var comments = db.AB_DiscussionComments.Where(c => c.Discussion_ID == Discussion_ID);



        DiscussionVM model = new DiscussionVM()
        {

            Disussion_ID = discussion.Discussion_ID,
            Discussion_Title = discussion.Discussion_Name,
            Discussion_Description = discussion.Discussion_Name,
            Discussion_CreateBy = db.AspNetUsers.Find(discussion.CreatedBy).UserName,
            Discussion_CreateDate = discussion.CreatedDate,

            Comments = comments.Select(c => new CommentVM()

            {
                Comment_ID = c.Comment_ID,
                Comment_Description = c.Comment_Discription,
                Comment_CreateBy = db.AspNetUsers.Find(c.CreatedBy).UserName,                    
                Comment_CreateDate = c.CreatedDate

            })

        };



        return View(model);
    }

Getting following error

Method 'Project.Models.AspNetUser Find(System.Object[])' declared on type 'System.Data.Entity.DbSet1[Project.Models.AspNetUser]' cannot be called with instance of type 'System.Data.Entity.Core.Objects.ObjectQuery1[Project.Models.AspNetUser]'

dimanche 30 août 2015

How to retrieve the datetime selected from datetimePicker from database in the edit section in Asp.Net MVC 3?

I want to retrieve the datetime selected at the time of create i.e date of birth in this date. I have used datetime picker for picking date from the calender.

Controller:

public ActionResult EditDependent(decimal id)
{
    if (Session["EMPLOYEEID"] == null)
        return RedirectToAction("Index");           

    Dependent dependent = db.Dependent.Find(id);
    //ViewBag.RelationData = new SelectList(db.Relation.OrderBy(r => r.Description), "Id", "Description");
    ViewBag.RelationData = new SelectList(db.Relation.ToList(), "Id", "Description",dependent.RelationId);
    ViewBag.Occupation = new SelectList(db.Occupation.ToList(), "Id", "Description",dependent.OccupationId);
    return View(dependent);
}

[HttpPost]
public ActionResult EditDependent(Dependent dependent)
{
    if (Session["EMPLOYEEID"] == null)
        return RedirectToAction("Index");  
    if (ModelState.IsValid)
    {
        db.Entry(dependent).State = EntityState.Modified;
        PersonalInformationSystem.UpdateDependent(dependent.Id, Convert.ToInt32(Session["EMPLOYEECODE"]), dependent.Name,
                Convert.ToInt32(dependent.RelationId),Convert.ToDateTime(dependent.DOB), Convert.ToInt32(dependent.OccupationId), User.Identity.Name.ToString());
        return RedirectToAction("DependentList/" + Session["EMPLOYEEID"]);
    }
    return View(dependent);
}

Views:

<td>                   
  <div class="editor-label">
    @Html.LabelFor(model => model.DOB, "Date Of Birth")
  </div>
</td>
<td>
  <div class="editor-field">
    @Html.EditorFor(model => model.DOB)
        @Html.ValidationMessageFor(model => model.DOB)
  </div>
</td>

Model: public class Dependent { [Key] public decimal Id { get; set; } public string Name { get; set; } //[ForeignKey("RelationId")] public int RelationId { get; set; } [DataType(DataType.Date)] [Display(Name = "Event Date")] [DisplayFormat(DataFormatString = "{0:d}")] public DateTime DOB { get; set; }

    public int OccupationId{ get; set; }
    public int EmployeeCode { get; set; }
    public decimal EmployeeId { get; set; }
    public string EntryBy { get; set; }
     [DataType(DataType.Date)]
    [Display(Name = "Event Date")]
    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime LastModifiedDate { get; set; }

How to reload page without _layout query string parameter

Page url is in form

http://ift.tt/1NQrEZJ

Page contains button "reset layout" which invokes javascript code:

        window.location.reload();

How to reload page without _layout=somevalue2 parameter ? Is it possible/reasonable to use javascript for this ? This is ASP.NET MVC3 application. If javascript not reasonable, how to call server side controller for this ?

jquery and Bootstrap 3 are used.

mvc version problems (exists in both gac and temp asp.net)

I have a website that is running asp.net + mvc3 I have installed mvc 4 on my dev machine and since have removed it. since then I can't publish to my production server without getting this:

'error CS0433: The type 'System.Web.Mvc.WebViewPage' exists in both 'c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\6c0d160f\330c4242\assembly\dl3\122e2e49\00f3d8c1_b3d8cf01\System.Web.Mvc.DLL' and 'c:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Web.Mvc\v4.0_3.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll'

currently both machines have only asp.net mvc 3 installed. I have stopped the web server and deleted the temp files, didn't work.

any ideas? 10x Igal

samedi 29 août 2015

Error: An asynchronous module or handler completed while an asynchronous operation was still pending

I have a Controller Action method to Save user Details like below.

public async Task<ActionResult> SaveUser(ViewModel.VM_CreateUser user)
{
    var result = await _user.Save(userDetails);
    return Json(new { Success = String.IsNullOrEmpty(result) });
}

So far there is no issue in above 4 lines function.

public async Task<ActionResult> SaveUser(ViewModel.VM_CreateUser user)
{
    var result = await _user.Save(userDetails);
    new MailController().CreateUser(user.userDetails); //<==This is problem line of code.
}

and Below is my Mail Controller.

public class MailController : MailerBase
{
    public void CreateUser(ViewModel.VM_User user)
    {
        To.Add(user.EmailAddress);
        From = System.Configuration.ConfigurationManager.AppSettings["emailSender"];
        Subject = "Hi";
        Email("CreateUser", user).DeliverAsync();
    }
}

in the above code, I am facing problem when I execute the Email Sending code. I get below error message.

An asynchronous module or handler completed while an asynchronous operation was still pending

Please suggest the corrective action !!

The name 'ViewBag' does not exist in the current context while upgrading project

I made the mistake and run the upgrade package command at package manager console. Now i get a couple of errors.

The ./Views/Web.config is

<?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.2.3.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.Optimization"/>
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

The web.config is

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://ift.tt/1eW0XAj
  -->
<configuration>
  <configSections>
        <!-- For more information on Entity Framework configuration, visit http://ift.tt/1eigFsq -->
    <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
            <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true"/>
            <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true"/>
        <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true"/><section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true"/></sectionGroup></configSections>

  <connectionStrings>
    <!--<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\v11.0;Initial Catalog=aspnet-Backend-20150828141545;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Backend-20150828141545.mdf" providerName="System.Data.SqlClient"/>-->
  </connectionStrings>

  <appSettings>
    <add key="webpages:Version" value="2.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="PreserveLoginUrl" value="true"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.5"/>

    <httpRuntime targetFramework="4.5"/>


    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880"/>
    </authentication>

    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers"/>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>

  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <remove name="OPTIONSVerbHandler"/>
      <remove name="TRACEVerbHandler"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers></system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Spatial" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Http" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
            </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246"/>
        <bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246"/>
        <bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930"/>
      </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.2.3.0" newVersion="5.2.3.0"/>
      </dependentAssembly>
    </assemblyBinding>
  <!-- This prevents the Windows Event Log from frequently logging that HMAC1 is being used (when the other party needs it). --><legacyHMACWarning enabled="0"/><!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink
             to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it.
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
         --></runtime>
<system.net>
        <defaultProxy enabled="true"/>
        <settings>
            <!-- This setting causes .NET to check certificate revocation lists (CRL) 
                 before trusting HTTPS certificates.  But this setting tends to not 
                 be allowed in shared hosting environments. -->
            <!--<servicePointManager checkCertificateRevocationList="true"/>-->
        </settings>
    </system.net><dotNetOpenAuth>
        <messaging>
            <untrustedWebRequest>
                <whitelistHosts>
                    <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
                    <!--<add name="localhost" />-->
                </whitelistHosts>
            </untrustedWebRequest>
        </messaging>
        <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
        <reporting enabled="true"/>
    <!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. --><!-- For a complete set of configuration options see http://ift.tt/1dQGZDo --><openid>
        <relyingParty>
                <security requireSsl="false">
                    <!-- Uncomment the trustedProviders tag if your relying party should only accept positive assertions from a closed set of OpenID Providers. -->
                    <!--<trustedProviders rejectAssertionsFromUntrustedProviders="true">
                        <add endpoint="http://ift.tt/1dQGWY1" />
                    </trustedProviders>-->
                </security>
                <behaviors>
                    <!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
                         with OPs that use Attribute Exchange (in various formats). -->
                    <add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty"/>
                </behaviors>
            </relyingParty></openid></dotNetOpenAuth><uri>
        <!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
             which is necessary for OpenID urls with unicode characters in the domain/host name.
             It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. -->
        <idn enabled="All"/>
        <iriParsing enabled="true"/>
    </uri></configuration>

and the packages.config is

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.4.1.9004" targetFramework="net45" />
  <package id="DotNetOpenAuth.AspNet" version="4.3.4.13329" targetFramework="net45" />
  <package id="DotNetOpenAuth.Core" version="4.3.4.13329" targetFramework="net45" />
  <package id="DotNetOpenAuth.OAuth.Consumer" version="4.3.4.13329" targetFramework="net45" />
  <package id="DotNetOpenAuth.OAuth.Core" version="4.3.4.13329" targetFramework="net45" />
  <package id="DotNetOpenAuth.OpenId.Core" version="4.3.4.13329" targetFramework="net45" />
  <package id="DotNetOpenAuth.OpenId.RelyingParty" version="4.3.4.13329" targetFramework="net45" />
  <package id="EntityFramework" version="6.1.3" targetFramework="net45" />
  <package id="jQuery" version="2.1.4" targetFramework="net45" />
  <package id="jQuery.UI.Combined" version="1.11.4" targetFramework="net45" />
  <package id="jQuery.Validation" version="1.14.0" targetFramework="net45" />
  <package id="knockoutjs" version="3.3.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.Mvc.FixedDisplayModes" version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.OData" version="5.7.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebPages.Data" version="3.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebPages.OAuth" version="3.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebPages.WebData" version="3.2.3" targetFramework="net45" />
  <package id="Microsoft.Data.Edm" version="5.6.4" targetFramework="net45" />
  <package id="Microsoft.Data.OData" version="5.6.4" targetFramework="net45" />
  <package id="Microsoft.jQuery.Unobtrusive.Ajax" version="3.2.3" targetFramework="net45" />
  <package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.3" targetFramework="net45" />
  <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
  <package id="Modernizr" version="2.8.3" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net45" />
  <package id="System.Spatial" version="5.6.4" targetFramework="net45" />
  <package id="WebGrease" version="1.6.0" targetFramework="net45" />
</packages>

How am i supposed to fix that? Thank you

vendredi 28 août 2015

Unable to upload files if size is more than 4mb in asp.net mvc3

I am unable to ulpoad files if total size of files is more than 4mb in asp.net mvc3. I am using jquery.form.js to upload file and uses ajax to post the form to server side. It works fine if total size of files uploaded is less than 4 mb but if exceeds 4mb then its not posting the form to server side... My application's web.config is already configured to 1GB using maxRequestLength attribute of httpruntime tag.

Can anyone knows how to allow application to post larger files? Thanks

Passing RadioButton Value to Controller within bootstrap

I am trying to pass a radiobutton value to a controller. However I cannot seem to figure out how to get the value I pass through. I am not sure what to do with the controller.

Model that I use to keep the value

public class PendingTasksModel
{
    public string environmentName { get; set; }
}

View

<div class="col-md-3">
    <div class="btn-group-vertical pull-right" data-toggle="buttons">
         <label class="btn btn-primary" style="@displayOak">
             @Html.RadioButtonFor(model => model.environmentName, "OAK")
             OAK
         </label>
         <label class="btn btn-primary" style="@displayQa">
             @Html.RadioButtonFor(model => model.environmentName, "QA")
             QA
         </label>
         <label class="btn btn-primary" style="@displayProd">
             @Html.RadioButtonFor(model => model.environmentName, "PROD")
             PROD
         </label>
     </div>
 </div>

Controller

private ActionResult InitializeService(string option)
    {
        _binding = new BasicHttpBinding();
        if (option == "OAK")
        {
            _endpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["OAK"]);
        }
        else if (option == "PROD")
        {
            _binding.Security.Mode = BasicHttpSecurityMode.Transport;
            _endpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["PROD"]);
        }
        else
        {
            _binding.Security.Mode = BasicHttpSecurityMode.Transport;
            _endpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["QA"]);
        }
        _channel = new ChannelFactory<IEisIntegrationService>(_binding, _endpointAddress);

        try
        {
            _target = _channel.CreateChannel();


        }
        catch
        {
            if (_target != null)
            {
                ((ICommunicationObject)_target).Abort();
            }
        }
        return View();
    }

connection string not working in MVC3

I am trying to connect SQL server database in visual studio 2012, but this is not working. where I am doing with my connection. plz help. I searched topic but could not find the mistake. I am using windows authentication for SQL server.
this is my Web.config setting:

<connectionStrings>
    <add name="DefaultConnection"
         connectionString="server=.; database=sample; integrated security=SSPI"
         providerName="System.Data.SqlClient"/>
</connectionStrings>  

this is my Global.asax.cs setting:

protected void Application_Start()
     {
        Database.SetInitializer<MVCDemo.Models.DefaultConnection>(null);
        AreaRegistration.RegisterAllAreas();

        // Use LocalDB for Entity Framework by default
        Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

this is DefaultConnection.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;


namespace MVCDemo.Models
{
    public class DefaultConnection : DbContext
    {
         public DbSet<Employee> Employees { get; set; }
    }
}

EmployeeController.cs:

 public ActionResult Details(string id)
        {
            int li_id = Convert.ToInt32(id);
            EmployeeContext lo_employeeContext = new EmployeeContext();
            Employee lo_employee = lo_employeeContext.Employees.Single(emp => emp.EmployeeId == li_id); 

            return View(lo_employee);
        }    

this is employee model:

using System.ComponentModel.DataAnnotations.Schema;  
    namespace MVCDemo.Models
    {
        [Table("tbl_Employee")]
        public class Employee
        {
            public int EmployeeId { get; set; }
            public string Name { get; set; }
            public string Gender { get; set; }
            public string City { get; set; }
        }
    }  

Plz Help.

How to enable and disable MVC Required Field validation

I need to enable and disable the required field validation based on anchor tag click.

Here I showed some example

<div class="row">
        <div class="col1">
            @Html.DisplayNameFor(m => m.CustomText)
        </div>
        <div class="col2">
            @Html.TextAreaFor(m => m.CustomText)
            @Html.ValidationMessageFor(m => m.CustomText, null, new { @style = "color:red" })
        </div>
        <a href="javascript:void(0)" onclick="SelectOn();" class="button">ON</a>
        <a href="javascript:void(0)" onclick="SelectOff();" class="button">OFF</a>
</div>
<script type="text/javascript">
        $(document).ready(function () {
            var modVal = '@Modle.IsEnabled';
            if (modVal = 'false') {
                //Need to disable
            }
        });

        function SelectOn() {
            //Need to enable
        }

        function SelectOff() {
            //Need to disable
        }
</script>

MvcMusicStore database connection

I am following the asp.net MvcMusicStore tutorial and everything works fine but the data is not adding to MvcMusicStore.sdf...This is the page with that part of the tutorial that makes the connection to database: http://ift.tt/1ytqfhx The expected result should return a list with all of genres, but in my case I'm getting NULL values in MvcMusicStore.sdf Genres table.

SampleData.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcMusicStore.Models
{
    public class SampleData : DropCreateDatabaseIfModelChanges<MusicStoreEntities>
    {
        protected override void Seed(MusicStoreEntities context)
        {
            var genres = new List<Genre>
            {
                new Genre { Name = "Rock" },
                new Genre { Name = "Jazz" },
                new Genre { Name = "Metal" }
            };

            var artists = new List<Artist>
            {
                new Artist { Name = "Aaron Copland & London Symphony Orchestra" },
                new Artist { Name = "Aaron Goldberg" }
            };

            new List<Album>
            {
                new Album { Title = "A Copland Celebration, Vol. I", Genre = genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Aaron Copland & London Symphony Orchestra"), AlbumArtUrl = "/Content/Images/placeholder.gif" },
            }.ForEach(a => context.Albums.Add(a));
        }
    }
}

Web.config:

  <connectionStrings>
    <add name="MusicStoreEntities"
     connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf"
     providerName="System.Data.SqlServerCe.4.0"/>
  </connectionStrings>

Syntax Error in MVC view

This one gives me a syntax error at @question

What is wrong here?

@{
    string question = "Really delete?";

<link href="~/Content/sweetalert/sweetalert.css" rel="stylesheet" />
<script src="~/Content/sweetalert/sweetalert.min.js"></script>
<script>
    $(function () {
        $(".delete").on("click", function (e) {
            swal({
                text: @question,
                title: "Delete Confirm",
                //some other stuff...

how to implement custom validator like password does not contain firstname or lastname custom validation in MVC 4

i have three fields firstname,lastname and password in mvc application form ,how to implement custom validator like password does not contain firstname or lastname custom validation in MVC 4.

jeudi 27 août 2015

Binding ViewModel with a list of ViewModels including HttpPostedFileBase to controller action

Okay, so i'm gonna try my best to explain the problem i'm facing at the moment.

I want to have a create view, which is strongly typed to a ViewModel. The ViewModel has some properties, where one of them is a list, containing ViewModels of another kind. That ViewModel contains some more properties, plus a value of type HttpPostedFileBase.

The createView should contain a file input for each of the viewModels, in the List. All other properties are going to be hidden from the user. The only thing that needs user interaction is the HttpPostedFileBase.

The thing is, firstly, i cannot get EditorFor to create a file input, and believe me lord iv'e tried. Secondly, i need to do it for every entry in the list of the strongly typed viewModel (TestViewModel below), so it can bind the values back to the controller on post.

The reason im creating this, as a test project, is that i need to see what the HTML would look like, in order for the asp.net binder to be able to bind it to the controller post action.

Please, if you dont understand the problem above, feel free to ask questions. I will do my best to answer. Thanks !

Simplified example classes.

public class TestViewModel
{
    public string SomeString { get; set; }
    public int SomeInt { get; set; }
    public List<ImageViewModel> ImageViewModels { get; set; }
}

public class ImageViewModel
{
    [DataType(DataType.Upload)]
    public HttpPostedFileBase Value { get; set; }
}

Create View (simplified, i know. It's a test project)

@model WebApplication1.Models.TestViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>TestViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div>
            <table>
                <tr>
                    <th>Image</th>
                </tr>
                @for (int i = 0; i < Model.ImageViewModels.Count; i++)
                {
                    <td>@Html.EditorFor(m => m.ImageViewModels[i].Value)</td>
                }
            </table>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

bind two data models to one model in mvc

I'm creating MVC 5 application, in this application I'm joining multiple data table using one var model and bind that values to "DiscussionPreview_Model" model to list down data

this is controller class

   public ActionResult Discussion_Preview()
    {

        int Discussion_ID = 1;


        var discussion_preview = (from d in db.AB_Discussion
                                  where d.Discussion_ID == Discussion_ID
                                  join dc in db.AB_DiscussionComments on d.Discussion_ID equals dc.Discussion_ID
                                  join user_discussion in db.AspNetUsers on d.CreatedBy equals user_discussion.Id
                                  join user_comments in db.AspNetUsers on dc.CreatedBy equals user_comments.Id

                                  select new DiscussionPreview_Model
                                  {
                                      Disussion_ID = d.Discussion_ID,
                                      Discussion_CreateDate = d.CreatedDate,
                                      Discussion_CreateBy = user_discussion.UserName,
                                      Discussion_Title = d.Discussion_Name,
                                      Discussion_Description = d.Discription,
                                      Comment_ID = dc.Comment_ID,
                                      Comment_Description = dc.Comment_Discription,
                                      Comment_CreateDate = dc.CreatedDate,
                                      Comment_CreateBy = user_comments.UserName

                                  });


            return View(discussion_preview);
    }

this is my "DiscussionPreview_Model" model class

   public class DiscussionPreview_Model
    {

        DiscussionVM model1;
        CommentVM model2;

    }


    public partial class DiscussionVM
    {
        public int Disussion_ID { get; set; }
        public Nullable<System.DateTime> Discussion_CreateDate { get; set; }
        public string Discussion_CreateBy { get; set; }
        public string Discussion_Title { get; set; }
        public string Discussion_Description { get; set; }

        public IEnumerable<CommentVM> Comments { get; set; }

    }

    public partial class CommentVM
    {
        public int Comment_ID { get; set; }
        public Nullable<System.DateTime> Comment_CreateDate { get; set; }
        public string Comment_CreateBy { get; set; }
        public string Comment_Description { get; set; }
    }

This is View Page

 @model IEnumerable<albaraka.Models.DiscussionPreview_Model>

@{
    ViewBag.Title = "Discussion_Preview";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


@foreach (var discussion in Model.DiscussionVM)
{

<h3>>@discussion.Discussion_Title</h3>

<div>@discussion.Discussion_Description</div>
<div>@discussion.Discussion_CreateDate</div>
}

@foreach (var item in Model.CommentVM)
{

    <fieldset>
        <legend></legend>


        <h4>Comments</h4>
        <div class="display-field">@item.Comment_Description</div>
        <div class="display-field">@item.Comment_CreateBy : @item.Comment_CreateDate </div>

    </fieldset>
}

but this is not working properly, I tried to overcome this problem in many ways

Really appreciate can suggest a strong linq query approach

How to call a method from controller more once time? AJAX

Sorry if the question is really dumb, however, I couldn't find how to solve it.

I have a very simple methid in a controller:

public string ExactSeconds()
{
   string str = DateTime.Now.Second.ToString();
   return str;            
}

The view is simpler than the method:

<p id="rData"></p> 
<p id="qqqqq">click me!</p> 

JavaScriptCode:

<script type="text/javascript">
  $(document).ready(function () {
    $('#qqqqq').click(function () {
        alert('');
        var url = "/Home/ProverbPartialView";
        $.get(url, null, function (data) {                
            $.get(url, null, function (data) {
                $("#rData").html(data);
            });

        });

    });
 });

However, When I click at id="qqqqq", then it just uploads data(seconds) just for the first time. Then if I click the second time and the next times, then alert('') works perfectly, however it is not called method ExactSeconds, that is I cannot see updated seconds at the view.

How to call method ExactSeconds() always when I click at #qqqqq?

Remove unmatched records from list

I have a class ABC like this

public class ABC{
public int Id {get;set;}
public int UserCount {get;set;}
}

Now I add following records to a list of type ABC

List<ABC> lstABC = new List<ABC>();
lstABC.Add(new ABC(){Id=1,UserCount=5});
lstABC.Add(new ABC(){Id=2,UserCount=15});
lstABC.Add(new ABC(){Id=3,UserCount=3});
lstABC.Add(new ABC(){Id=4,UserCount=20});
lstABC.Add(new ABC(){Id=5,UserCount=33});
lstABC.Add(new ABC(){Id=6,UserCount=21});

I've another list of type int

List<int> lstIds = new List<int>();
lstIds.Add(1);
lstIds.Add(3);
lstIds.Add(4);

Now i want to remove all the items from lstABC whose Id's do not match in lstIds without using any loops. What is the most optimized way to do this?

mercredi 26 août 2015

'IEnumerable<>' does not contain a definition for '' and no extension method '' accepting a first argument of type 'IEnumerable<>' could be found

I want to create online forum like below image


enter image description here


this is my Controller method

public ActionResult Discussion_Preview()
{

    int Discussion_ID = 1;


   var discussion_preview = (from d in db.AB_Discussion
                              where d.Discussion_ID == Discussion_ID
                              join dc in db.AB_DiscussionComments on d.Discussion_ID equals dc.Discussion_ID
                              join user_discussion in db.AspNetUsers on d.CreatedBy equals user_discussion.Id
                              join user_comments in db.AspNetUsers on dc.CreatedBy equals user_comments.Id
                              select new DiscussionPreview_Model
                              {
                                Disussion_ID = d.Discussion_ID,
                                Discussion_CreateDate = d.CreatedDate,
                                Discussion_CreateBy = user_discussion.UserName,
                                Discussion_Title = d.Discussion_Name,
                                Discussion_Description = d.Discription,
                                Comment_ID = dc.Comment_ID,
                                Comment_Description = dc.Comment_Discription,
                                Comment_CreateDate = dc.CreatedDate,
                                Comment_CreateBy = user_comments.UserName

                              });



    return View(discussion_preview);
}

Model Class

public class DiscussionPreview_Model
{
    public int Disussion_ID { get; set; }
    public Nullable<System.DateTime> Discussion_CreateDate { get; set; }
    public string Discussion_CreateBy { get; set; }
    public string Discussion_Title { get; set; }
    public string Discussion_Description { get; set; }

    public int Comment_ID { get; set; }
    public Nullable<System.DateTime> Comment_CreateDate { get; set; }
    public string Comment_CreateBy { get; set; }
    public string Comment_Description { get; set; }

}

View Page

@model IEnumerable<prjct.Models.DiscussionPreview_Model>

@{
    ViewBag.Title = "Discussion_Preview";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

 <h3>@Html.DisplayFor(model => model.Discussion_Title)</h3>

<div>@Html.DisplayFor(model => model.Discussion_Description)</div>
<div>@Html.DisplayFor(model => model.Discussion_CreateDate)  @Html.DisplayFor(model => model.Discussion_CreateDate)</div>

@foreach (var item in Model)
{

    <fieldset>
        <legend></legend>

        <h4>Comments</h4>
        <div class="display-field">@item.Comment_Description</div>
        <div class="display-field">@item.Comment_CreateBy : @item.Comment_CreateDate </div>

    </fieldset>
}

When debug above application I'm getting below error message

'IEnumerable' does not contain a definition for 'Discussion_Title' and no extension method 'Discussion_Title' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?)

How to format column of data in excel generated from MVC 3 application ?

Basically my MVC 3 application generates an Excel file upon user request. My problem, one of the columns contains data like the following "01/2015"... this represents a work-week of a year. This property is a string value in my application and displays perfectly on the screen within the application but once in Excel file, 01/2015 displays as Jan-2015. So workweeks 01 - 12 display as months Jan - Dec. I cannot use a macro as this file will be generated new each time from the MVC 3 application. I being advised to create an exe file, using this exe file to locate the excel and run it allowing the exe to alter the data or column . Unfortunately I have no idea how or where to start on that option ? Any ideas ?

ASP.NET How to open a folder at server side?

I'm trying to open folder location from code behind

  Process prc = new Process();
                prc.StartInfo.UseShellExecute = true;
                prc.StartInfo.FileName = @"\\Shared\FolderName\test";
                prc.Start();

After that I got it I couldn't achieve by using Shell32 class or Process.Start on server side as well as adding link to path cant be used because of the security problem so how can achieve this problem ?

Thanks for your help

ajax call with MVC partial view

I am trying to make an ajax call to get data and to Modify DOM.

here is my controller/ action looks like

   [HttpGet]
public ActionResult Index(int id)
{
// some code
return PartialView(Custom Object);
}

here is my Index View looks like

@Model CustomObject
    @foreach(loop thru Model)
    {
// add some other elements
}
if(Model.Count==0){
<script>some script</script>
}else{
<script>variable = '<div></div>'</script>
}

here is main view code

<script>var variable ='';</script>
<script>$('element').html(variable)</script>
<tbody id="tbodyId">
@RenderAction("Index");
<tbody>

here is my Ajax Call. I was trying to do

function test(id){
$.ajax({
type:'Get',
url:'/Home/Index?id='+id,
datatype:'html'
})
.done(function(data){
$('#tbodyId').html(data);
});
}

My issue is from the above ajax call it is not appending the script element from partial view.

I tried different ways from javascript side. But, im not sure whether im doing it right way or not. So, i need some suggestions from leads.

here is the other way i tried. but no luck

var scriptElement = document.createElement('script');
            scriptElement.innerHTML = $('#tbodyId').last().html();
            document.getElementById('#tbodyId').appendChild(scriptElement);

any help would be appreciated. Thanks!!

if block not working as expected in jQuery

Following jQuery function is being called from a View in an ASP.Net MVC3 project:

function ValidateRequestor() {
    var regex = /^[A-Za-z0-9]*$/;

    var frstNameval = $('[id*=FirstName]').val();
    if (!(/[a-z]/i.test(frstNameval))) {
        $('[id*=FirstName]').val("");
        $('[id*=FirstName]').focus();
        alert("Please specify a proper first name.");
        return false;
    }
    if (frstNameval == '') {
        alert("Please specify a first name.");
        return false;
    }
    var lstNameval = $('[id*=LastName]').val();
    if (!(/[a-z]/i.test(lstNameval))) {
        $('[id*=LastName]').val("");
        $('[id*=LastName]').focus();
        alert("Please specify a proper last name.");
        return false;
    }
    if (lstNameval == '') {
        alert("Please specify a last name.");
        return false;
    }

//    var Approvedval = $('#_SelectedGeography').val();
//    //debugger;
    if ($('#_SelectedGeography').val() == '') {
        alert("Please specify Approval Group.");
        return false;
    }
    debugger;
    if ($('#TextFAFM').length > 0) {
        if ($('#TextFAFM').val().length>0) {
            return true;
        }
        else if ($('#TextFAFM').val() == '') {
            alert("Please specify Financial Analyst.");
            return false;
        }        
    }
    else
        return true;
}

However the below block of code is not working as expected:

if ($('#TextFAFM').length > 0) {
            if ($('#TextFAFM').val().length>0) {
                return true;
            }
            else if ($('#TextFAFM').val() == '') {
                alert("Please specify Financial Analyst.");
                return false;
            }        
        }

The block which returns True is not getting executed. Please help.

mardi 25 août 2015

HTTPPostedFileBase always return null in controller

I have checked various answer for this, but none of them works for me, my code in .cshtml is as follows:

<input type="file" name="PostedNRLFile" />

and then in controller I have

 public JsonResult SaveRecord(NewAuditLetterViewModel viewModel, FormCollection all, string hvalue, HttpPostedFileBase PostedNRLFile)

Which is always null, Please help me in this.

I have already tried few things like creating a property in viewmodel, this is also null. Also used new { enctype = "multipart/form-data", id = "documentForm" } in my beginform tag. Also checked their is only one tag in source.

Instantiating the class but declared as an interface

Lets just say i have this interface and repository

Interface :

interface ICustomerRepository
    {

Repository that implements the interface

public class CustomerRepository:ICustomerRepository
    {      

In controller, i declared an instance of the interface,

private ICustomerRepository repository = null;

can someone explain the concept of this line?

this.repository = new CustomerRepository();

Still learning here, need inputs

ASP.NET MVC Help trying to convert a list to Javascript Array

I'm using ASP.NET MVC (with Razor) and JQuery

I have a list of strings in my controller and I render the partial view passing in the model with the below list.

List<string> list = new List<string>();
list.Add("test1");
list.Add("test2");

On client side I have:

<div id = "test", test-att = @Html.Raw(Json.Encode(Model.list)) />

In my javascript file I do:

var javascriptArray = $('#test').attr('test-att');

I'm expecting a result ["test1", "test2"] but I'm seeing "["test1", "test2"]"

Any ideas on how to fix this?

Method not found System.Web.WebPages.Html.HtmlHelper.ObjectToDictionary(System.Object)

I'm working with MVC for the first time in my life. I'm trying to build a grid, but I get this error when i'm trying:

enter code hereMethod not found: 'System.Collections.Generic.IDictionary`2<System.String,System.Object> System.Web.WebPages.Html.HtmlHelper.ObjectToDictionary(System.Object)'.

This is my line ih html code that triggers the error:

enter code here <div id="grid">
        @grid.GetHtml(tableStyle: "web-grid", columns: columns, footerStyle: "pagerajax")
    </div>

I already tried to modify the references System.Web.WebPages, but it did not work. I'm using MVC3 in this project.

PS: Sorry for my bad english, guys.

asp.net c# Controller acting weird

First of, the name of this question is not very good but I could not think of a better one. I'm working a project where I report hours perday, and on diffrent projects.

This is how it looks like. enter image description here

But the problem is now, if I would submit it it would end up like this.

enter image description here

Like we can see here on the summary of the month, that on the secound date it duplicates the project and shows it up twice, this happends if I add more dates as well. But it never happends on the first date.

I've been debugging it, but I do not see any diffrent behavior from when it were ran the first time, all the values are the same etc.

This is the controller

public ActionResult TimeReport(FormCollection form, Guid? id)
    {
        ViewDataDictionary vd = new ViewDataDictionary
        {
            ["projects"] = new DatabaseLayer().GetConsultantProjects(Constants.CurrentUser(User.Identity.Name)),
            ["id"] = 1,
            ["showDescription"] = true
        };
        ViewData["vd"] = vd;

        NewTimeReportModel projectData = new NewTimeReportModel();

        if (form != null && form.AllKeys.Contains("delete"))
        {
            new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
            LoadDefaultSettings(projectData);
            ViewData.Model = projectData;
            return View();
        }

        if (id.HasValue && (form == null || form.AllKeys.Length == 0))
        {
            using (DatabaseLayer db = new DatabaseLayer())
            {
                var timeReport = db.GetTimeReport(id.Value);
                projectData = new NewTimeReportModel(timeReport);
                if (projectData.Projects.Count == 1)
                    projectData.Projects[0].Hours = null;
            }
        }
        else if (form == null || form.AllKeys.Length == 0)
        {
            LoadDefaultSettings(projectData);
        }
        else
        {
            //Takes all the dates that is being sent from the view and put into a string.
            string input = (form["date"]);
            input = input.Trim();
            string[] dates = input.Split(' ');

            //Foreach to loop over all the dates, also rebuilds the string to look like yy-mm-dd so we can parse it to a datetime
            foreach (string result in dates.Select(date => date.Substring(0, 2) + '-' + date.Substring(2, 2) + "-" + date.Substring(4, 2)))
            {
                DateTime reportDate;
                if (!DateTime.TryParse(result, out reportDate))
                {
                    ModelState.AddModelError("Date", "Felaktikt datum");
                }

                var projectNumbers = (from x in form.AllKeys
                    where x.Contains("_")
                    select x.Substring(x.IndexOf('_'))).Distinct();

                projectData.Times = new TimeReportTimes(form["startTime"], form["endTime"], form["breakTime"], ModelState);
                projectData.Date = reportDate;

                //Checks to see if we did choose a project.
                var enumerable = projectNumbers as string[] ?? projectNumbers.ToArray();
                if (!enumerable.Any())
                {
                    ModelState.AddModelError("Projekt", "Inga projekt valda...");
                }
                else
                {
                    int emptyHours = 0;

                    foreach (string projectNumber in enumerable)
                    {

                        projectData.Projects.Add(new NewTimeReportModel.Project
                        {
                            Description = form["description" + projectNumber],
                            Hours = null,
                            ProjectId = Guid.Parse(form["project" + projectNumber])
                        });

                        string hourString = form["hours" + projectNumber];
                        if (string.IsNullOrEmpty(hourString))
                        {
                            emptyHours++;
                            projectData.Projects[projectData.Projects.Count - 1].Hours =
                                projectData.Times.WorkedHours;
                        }
                        else
                        {
                            if (!projectData.Projects[projectData.Projects.Count - 1].SetHours(hourString))
                            {
                                ModelState.AddModelError("hours_" + projectNumber, "Felaktig antal timmar");
                            }
                        }
                    }
                    //Checks so the hours are right.
                    if (emptyHours > 1 || (emptyHours == 0 && projectData.Projects.Sum(x => x.Hours) != projectData.Times.WorkedHours))
                    {
                        ModelState.AddModelError("hours_" + enumerable.First(),
                            "Antalet timmar stämmer ej överrens");
                    }

                    //Checks so the worked hours is bigger than 0
                    if (projectData.Projects.Any(x => x.Hours <= 0))
                    {
                        ModelState.AddModelError("hours_" + enumerable.First(),
                            "Antalet timmar måste vara större än noll");
                    }

                    if (!string.IsNullOrEmpty(form["ReportId"]))
                    { 
                        projectData.ReportId = Guid.Parse(form["ReportId"]);
                    }

                    if (ModelState.IsValid)
                    {
                        //saves the report to the database
                        projectData.SaveToDatabase(Constants.CurrentUser(User.Identity.Name));
                        //Saves ViewData To true so we know in the view it's been posted.
                        ViewData["posted"] = true;

                        projectData = new NewTimeReportModel();
                        LoadDefaultSettings(projectData);
                    }
                    else if (projectData.Projects.Count == 1)
                    { 
                        projectData.Projects[0].Hours = null;
                    }
                }
            }
        }

        var missingdays = new DatabaseLayer().GetConsultantMissingDays(Constants.CurrentUser(User.Identity.Name));
        if (missingdays.Count == 0)
        {
        }
        else
        {
            ViewBag.MissingDays = missingdays;
        }

        ViewData.Model = projectData;

        return View();
    }

Not able to call client method on OnDisconnected

I've a disconnect method in TestHub(which is inherited by Hub) class for signal R. I'm not able to call javascript method fnDeleteCustomer from OnDisconnected method, however same same js method gets called on Connect method. What I'm doing wrong?

 public override Task OnDisconnected()
        {
            try
            {
                 var customer = ConnectedUsers.Find(x => x.ConnectionID == Context.ConnectionId);
                if (customer!=null)
                {
                  Clients.Client(customer.ConnectionID).fnDeleteCustomer(customer.UserId);
                  return base.OnDisconnected();
                }
            }
            catch { };
            return null;
        }

DatePicker doesn't work with me

DatePicker doesn't work with my code:

<div class="row">
     <div class="col-sm-2">
         <label  class="control-label">Date d'ouverture</label>
     </div>

    <div class ="col-sm-6">
        @Html.TextBoxFor(model => model.ouvtik, new { @class = "datepicker form-control  col-sm-6", placeholder = "Cliquez pour sélectionner la date" })


        @Html.ValidationMessageFor(model => model.ouvtik)
    </div></div>

and also in the same view i have this :

    <script src="js/jquery-1.9.1.min.js"></script>
    <script src="js/bootstrap-datepicker.js"></script>
    <script type="text/javascript">
        $(function () { // will trigger when the document is ready
            $('.datepicker').datepicker(); //Initialise any date pickers
        });</script>

/script>
<script type="text/javascript" src="@Url.Content("~/ScriptsDatePickerReady.js")></script>

in my model I have this :

[DataType(DataType.Date)]
    public DateTime ouvtik { get; set; }

Please can anyone help me.. Thank you

ViewModel replacement for complex Anonymous Object

So im working with this complex anonymous object

        var result = new 
            {    
                percentage = "hide",
                bullets = (string)null,
                item = new [] {
                    new {
                        value = 16,
                        text = "Day",
                        prefix = (string)null,
                        label = (string)null
                    },
                    new {
                        value = 41,
                        text = "Week",
                        prefix = (string)null,
                        label = (string)null
                    },
                    new {
                        value = 366,
                        text = "Month",
                        prefix = (string)null,
                        label = (string)null
                    }
                }
            };

And I want to convert it into a ViewModel and return it as JSON from a rest API.

What I would like to know is

  1. How do I represent this as a model including the array item entries
  2. How do I then add array items to the array once an instance of the model is created
  3. Does the model need a constructor to initialize the array.

Any help or examples you could provide would be great.

lundi 24 août 2015

Visual Studio : ASP.Net MVC4 project publishing missing dlls

Following dlls are missing while publishing a ASP.Net MVC 4 project.

System.Net.Http.Formatting.dll 
System.Web.Http.dll 
System.Web.Http.WebHost.dll

Any idea ?

Note :
Am publishing my files to a local path. There am not able to find these dlls in bin folder. And when hosted in an IIS, getting the error as dll is missing.

Unable to post to a new action method via .Ajax right after a successful XMLHttpRequest in IE 10

I am adding a new feature in my app which lets users to complete a process in steps.

Step1 select dropdown value

hit next button and step 2 (ajax request loads and renders a partial view, rendering a tree view)

hit next button

step 3 (upload a file via XMLHttpRequest)

hit next button

Step 4(another ajax request is made to render a partial view) For some reason this request will never hit the controller action method. Whats weird is if I post to the action method in step 2, it will post successfully but I have different action for this step.

I am getting the following warnings in IE 10 Developer tools

SEC7127: Redirect was blocked for CORS request.

XMLHttpRequest: Network Error 0x800c0014, A redirection problem occurred. SCRIPT7002: XMLHttpRequest: Network Error 0x800c0014, A redirection problem occurred.

The above errors seem to be related to the XMLhhtprequest before this step. I have tried to set the XMLhttprequest to NULL or try to dispose it upon its success event. I dont understand in Step 4 I can still post to step 2's action but not a different one?

step 3

  function handleFiles() {

        var formdata = new FormData(); //FormData object
        var xhr = new XMLHttpRequest();
        xhr.open('POST', fileUploadURL);
        xhr.setRequestHeader('Content-type', 'multipart/form-data');

        //Appending file information in Http headers
        xhr.setRequestHeader('X-File-Name', document.getElementById('myFile').files[0].name);
        xhr.setRequestHeader('X-File-Type', document.getElementById('myFile').files[0].type);
        xhr.setRequestHeader('X-File-Size', document.getElementById('myFile').files[0].size);

        //Sending file in XMLHttpRequest
        xhr.send(document.getElementById('myFile').files[0]);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                $("input[id=filestoredname]").val(xhr.responseText);
                alert("file saved..");

            }
        }
                return false;
    }

var instrumentSelectionUrl = '@Url.Action("Step2", "ErrorCode")';//step2
var finalTreeViewUrl = '@Url.Action("renderFinalTree", "ErrorCode")';//step3
var fileUploadURL = '@Url.Action("UploadFiles", "ErrorCode")';//step3


$(function () {
    $('form').stepy({
        backLabel: '<<',
        nextLabel: '>>',
        finishButton: false,
        next: function (index) {
            alert(index);
            var v = $("#InsIdLst").chosen().val();
            if (v == null && index == 2) {
                alert("Please select an Instrument");
                return false;
            }
            if (v != null && index == 2) {
                var overlay = $('<div></div>').prependTo('body').attr('id', 'overlay');
                $.ajax({
                    type: 'POST',
                    url: instrumentSelectionUrl,
                    cache: false,
                    datatype: "html",
                    data: $("form").serialize(),
                    success: function (result) {
                        $("#errorCodes").html(result);
                        overlay.remove();
                    }
                });
            }
            if (index == 4) {
                alert("try..");
                $.ajax({
                    type: 'POST',
                    url: finalTreeViewUrl,
                    cache: false,
                    datatype: "html",
                    data: $("form").serialize(),
                    success: function (result) {
                        $("#errorCodesSave").html(result);
                    }
                });
            }

        }
    });
});

dimanche 23 août 2015

Another MVC3 A public action method 'yyyyy' was not found on controller 'xxxxx.Controllers.AccountController'

I know it has been asked many many times, but we have just upgraded our server from 2003 to 2012, and suddenly our email is flooded with thousands of email with this error even users does not appear to see these errors (We are using ELMAH to handle error emailing)

The patterns seem to be:

  1. it is looking for "A public action method 'Login' was not found on controller 'appName.Controllers.AccountController" but there is no where in the code is calling 'login' (got heaps of these)
  2. We also start getting "'/apple-touch-icon-xxxx.png' was not found" error but again we don't code for Apple.

This is our RegisterRoutes code:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );


            //Custom route for Error hander (ELMAH)
            routes.MapRoute(
            "ErrorHandler", // Route name
            "{*path}",      // URL
            new { controller = "Error", action = "Index" }
            );

These ALL a bit strange to me, can anyone suggest what should I start looking at?

Thanks in advance. WM

How to save data dynamically from a View in MVC5

I want to build a Questionnaire MVC5 project. I have a MSSQL database with several tables like: Employee, Questions, Results ...

I made a new MVC5 project, I add it the model base on my database and I manage all CRUD operations need it.

Now I made an view for Questionar :

@model IEnumerable<ChestionarMVC.Models.FormQuestion>

@{
    ViewBag.Title = "Chestionar";
}

<h2>Chestionar</h2>

    @foreach (var item in Model)
    {
   @Html.Partial("_Chestionar",item)
    }
<input id="Submit1" type="submit" value="submit" />

And a partialView to show each question with 2 text area, one for the answer and one for some aditional info :

@model ChestionarMVC.Models.FormQuestion

<table border="1" style="width:100%">

        <tr>
            <td>
                @Html.DisplayFor(modelItem => Model.Question)
            </td>

        </tr>
        <tr>
            <td>
                Raspuns <br />
                <textarea id="TextArea1" rows="2" cols="80" style="width:800px; height:100px;"></textarea>
            </td>
        </tr>
        <tr>
            <td>
                Document <br />
                <textarea id="TextArea2" rows="2" cols="80" style="width:400px"></textarea>
            </td>
        </tr>
</table>

Now I want to save in the tblResults the QuestionID, Answer and Document. In webforms I made a usercontrol, then I used Foreach usercontrol , and saved to database.

In MVC how can I save all?

OWIN | Get new Access Token when Access token gets expired

I have implemented OWIN authentication process in my project. Every thing works fine as I am able to get the access token, expiration time, the only issue I am facing is that I am start getting 401 error after 1 day because access token get expired. I think, I have to add a Refresh token with the login authentication process and the need to get the access token using that refresh token. Please help me in this context, unable to find any solution. Please have a look on below code what I have actually did.

Startup.cs

public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {

            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);

        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }

Interceptor File:

var _responseError = function (rejection) {
    if (rejection.status === 401) {
        $location.path('/login');
    }
    return $q.reject(rejection);
}

Currently I am just redirecting the user to login page but I want to get the new access token.

samedi 22 août 2015

Asp.net mvc project give me internal server error after publisihng

after publishing asp.net mvc project i noticed that in localhost in debug mode when call link http://localhost:56881/CPanel/login?role=form it return login view normally .

but after publishing it when try to call http://ift.tt/1EMG06d it gave me 500 - Internal server error.

//Login Action >> CPanel Controller 
  public ActionResult login() 
    {
        return View();
    }

    [HttpPost]
    public ActionResult login(FormCollection customer, string ReturnUrl) 
    {
        ViewBag.isError = false;
        if (Session["SystemAdmin"] == null)
        {
            var u = new Egx.EgxBusiness.Inventory.User() { USER_NAME = customer["EMAIL_ADDR"] }.Search();
            Crypto.VerifyHashedPassword(u[0].PASSWORD, customer["password"]);
            if (u.Count > 0 && Crypto.VerifyHashedPassword(u[0].PASSWORD, customer["password"]))
            {
                var c = new Customers() { EMAIL_ADDR = customer["EMAIL_ADDR"] }.Search();
                FormsAuthentication.SetAuthCookie(c[0].CUST_NAME, false);
                Session["_customer"] = c[0];
                if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")
                    && !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\")) { return Redirect(ReturnUrl); }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            else
            {
                ViewBag.isError = true;
                return View();
            }
        }
        else 
        {
            var c = new Customers() { EMAIL_ADDR = customer["EMAIL_ADDR"] }.Search();
            if (c.Count == 0) { c = new Customers() {CUST_CODE=customer["EMAIL_ADDR"] }.Search(); }
            if (c.Count > 0)
            {
                Session["_customer"] = c[0];
                     return RedirectToAction("Index");
             }
            else
            {
                ViewBag.isError = true;
                return View();
            }
        }
    }

Login View

@using (Html.BeginForm("login", "CPanel", new { ReturnUrl = Request.QueryString["ReturnUrl"], role = "form" }))
                    {
                         if (Request.QueryString["r"] != null) { <input type="hidden" value="@Request.QueryString["r"]" name="r"/> }
                            <div class="form-group">
                                <input  class="form-control" placeholder="E-mail" name="EMAIL_ADDR" type="text" autofocus>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="Password" name="password" type="password" value="" @Html.Raw(EgxNMWeb.AuthSystemAdmin.isSystemAdmin()? "disabled":string.Empty)>
                            </div>
                            <div class="checkbox">
                                <label>
                                    <input name="remember" type="checkbox" value="Remember Me">Remember Me
                                </label>
                            </div>
                            <!-- Change this to a button or input when using this as a form -->
                            <input type="submit" value="Login" class="btn btn-lg btn-success btn-block" />
                            @Html.Raw(EgxNMWeb.AuthSystemAdmin.isSystemAdmin()? "<a href="+Url.Action("Index","Finance")+">ماليات</a>":string.Empty)
                    }

Passing data to an EditorTemplate

I'm a newbie learning MVC and your help would be much appreciated. I have two models, Firms and Address. I'm trying to have a simple form where someone can add Firm details.

When the Firm Form is loaded, an Editor template containing Address model is Rendered. The problem I'm having is a straight forward one. I've even seen solutions to it on stack overflow but in my case it wont work (strange). When I'm passing new Innuendo.Models.AddressModel() to the Address Template, during Postback the ModelState.IsValid is false and Model.Address is still set to null. What am I doing wrong?

Firm View @model Innuendo.Models.FirmModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>FirmModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div>
            @Html.Partial("~/Views/shared/EditorTemplates/_Address.cshtml", new Innuendo.Models.AddressModel())
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.LogoPath)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LogoPath)
            @Html.ValidationMessageFor(model => model.LogoPath)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Editor Template _Address @model Innuendo.Models.AddressModel

<div class="editor-label">
    @Html.LabelFor(model => model.HouseName)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.HouseName)
    @Html.ValidationMessageFor(model => model.HouseName)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Street)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Street)
    @Html.ValidationMessageFor(model => model.Street)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Town)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Town)
    @Html.ValidationMessageFor(model => model.Town)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.County)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.County)
    @Html.ValidationMessageFor(model => model.County)
</div>

Firm Controller

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(FirmModel firmmodel)
        {
                        if (ModelState.IsValid)
            {

                firmmodel.FirmId = Guid.NewGuid();    
                db.Firms.Add(firmmodel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(firmmodel);
        }

Firms Model

[Table("Firms")]
    public class FirmModel
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public Guid FirmId { get; set; }

        [Display(Name = "Firm Name")]
        [Required]
        [StringLength(250)]
        public string Name { get; set; }

        [Required]
        public virtual AddressModel Address { get; set; }

        [StringLength(250)]
        public string LogoPath { get; set; }
    }

**Address Model**

 [Table("Addresses")]
    public class AddressModel
    {
        [Key]
        [HiddenInput(DisplayValue = false)]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public Guid AddressId { get; set; }

        [Required]
        [Display(Name = "House Name/Number")]

        [StringLength(250)]
        public string HouseName { get; set; }

        [StringLength(250)]
        [Required]
        public string Street { get; set; }

        [StringLength(250)]
        [Required]
        public string Town { get; set; }

        [StringLength(250)]
        [Required]
        public string County { get; set; }
    }

How to create new page in MvcRazorToPdf?

My code for generating pdf file is this:

public ActionResult Print(int id)
{
var record = db.Records.Find(id);
return new PdfActionResult(record, (writer, document) =>
{
    document.SetPageSize(new Rectangle(600f, 400f, 90));
    document.NewPage();
});

}

How to return a PdfActionResult with multiple pages for each record if i have a list of records? For example: public ActionResult Print(int id) { var records = db.Records.ToList();

// How to return pdfactionresult for each record?

return new PdfActionResult(record, (writer, document) =>
{
    document.SetPageSize(new Rectangle(600f, 400f, 90));
    document.NewPage();
});

}

asp.net mvc bundling or caching

All,

I have couple of questions for the optimization of application and i hope GURUs will help me to select the best approach.

Bundling and Minification

  1. When working with asp.net mvc, I believe that we have bundling. With reference to following lin k, http://ift.tt/1tHBXlU

  2. ASP.NET Optimization framework caches the bundle response in HttpContext.Cache and uses a CacheDependency.

  3. The bundle file name is a hash of the bundle contents which ensures the URL changes when any of the bundle files are modified. The bundle's virtual path is used as the cache key.

  4. Bundles set the HTTP Expires Header one year from when the bundle is created.

Caching in Web.config:

<configuration>
<system.webServer>
<caching>
  <profiles>
    <add extension=".css" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange"  />
    <add extension=".js" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
  </profiles>
</caching>
</system.webServer>
<configuration>

My basic question is

  1. which approach is better to optimize performance from both above mentioned techniques? and Why?
  2. What will be the impact of both, preferring Bundling and Minification on Caching js Files in Web.Config and preferring Caching js files on Bundling and Minification?

Thanks.

vendredi 21 août 2015

how to make ajax call to get partial view contains javascript?

I am trying to make an ajax call to get data and to Modify DOM.

here is my controller/ action looks like

   [HttpGet]
public ActionResult Index(int id)
{
// some code
return PartialView(Custom Object);
}
here is my Index View looks like

@Model CustomObject
    @foreach(loop thru Model)
    {
// add some other elements
}
if(Model.Count==0){
<script>some script</script>
}else{
<script>variable = '<div></div>'</script>
}

here is main view code

<script>var variable ='';</script>
<script>$('element').html(variable)</script>
<tbody id="tbodyId">
@RenderAction("Index");
<tbody>

here is my Ajax Call. I was trying to do

function test(id){
$.ajax({
type:'Get',
url:'/Home/Index?id='+id,
datatype:'html'
})
.done(function(data){
$('#tbodyId').html(data);
});
}

My issue is from the above ajax call it is not appending the script element from partial view.

I tried different ways from javascript side. But, im not sure whether im doing it right way or not. So, i need some suggestions from leads.

here is the other way i tried. but no luck

var scriptElement = document.createElement('script');
            scriptElement.innerHTML = $('#tbodyId').last().html();
            document.getElementById('#tbodyId').appendChild(scriptElement);

any help would be appreciated. Thanks!!

jeudi 20 août 2015

Access Property of a List Item Model from Javascript

I am using Javascript to edit the property of a row in a List of items and i am following a HTML view like this

ON edit button click i am showing a popup and on Save event of popup i want to set the properties of a selected row .

From html console i can see naming pattern is like name=[1].IsVerified [2].isVerified etc or in general [counter].Property But when i try to access element using JQUery i am not getting the element

    @model  IList<RoyaltyDb.Models.VerifyLicensorModel> 
    <table class="table">
        <tr>
            <th>
              Licensor
            </th>
            <th>
             Address
            </th>
            <th>
                Status
            </th>
            <th>
                Verify
            </th>
        </tr>
      @for (int i = 0; i < Model.Count(); i++) 
      {
            <tr>
                <td>         
                    @Html.HiddenFor(m => m[i].Licensor)                                                    
                    @Html.DisplayFor(m => m[i].Licensor)                                
                </td>
                <td>
                    @Html.TextAreaFor(m => m[i].Address)
                </td>
                <td>                              
                    @Html.LabelFor(m => m[i].IsVerified)                         
                    @Html.CheckBoxFor(m => m[i].IsVerified, new { @disabled = "disabled" })
                    <br />                  
                    @Html.HiddenFor(m => m[i].ActionId)
                    @Html.HiddenFor(m => m[i].ReferenceId)                                
                </td>
                <td>
                    <a onclick="SetProperties('@Model[i].Licensor')" class="btn">Verify</a>
                </td>
            </tr>
        }
    </table>


    <!-- Modal HTML -->
    <div id="VerifyLicensorModal" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title">Verify  Licensor</h4>
                    <input type="hidden" id="targetPopup" />
                </div>
                <div class="modal-body" id="VerifyLicensorDetails">

                </div>
                <div class="modal-footer">
                    <a class="btn btn-primary" onclick="confirmLicensor()">Confirm</a>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    function SetProperties(name)
    {
        //Showing a POPUp Here on element  VerifyLicensorModal
    }
    function confirmLicensor()
    {
       //Set the corresponding IsVerified checkbox to true
      //Set values of ActionId and ReferenceId params in the hidden fields 
      //ActionId  ReferenceId
    }

So how can i set the value of a property field from javascript

ajax call with MVC partial view

I am trying to make an ajax call to get data and to Modify DOM.

here is my controller/ action looks like

   [HttpGet]
public ActionResult Index(int id)
{
// some code
return PartialView(Custom Object);
}

here is my Index View looks like

@Model CustomObject
    @foreach(loop thru Model)
    {
// add some other elements
}
if(Model.Count==0){
<script>some script</script>
}else{
<script>variable = '<div></div>'</script>
}

here is main view code

<script>var variable ='';</script>
<script>$('element').html(variable)</script>
<tbody id="tbodyId">
@RenderAction("Index");
<tbody>

here is my Ajax Call. I was trying to do

function test(id){
$.ajax({
type:'Get',
url:'/Home/Index?id='+id,
datatype:'html'
})
.done(function(data){
$('#tbodyId').html(data);
});
}

My issue is from the above ajax call it is not appending the script element from partial view.

I tried different ways from javascript side. But, im not sure whether im doing it right way or not. So, i need some suggestions from leads.

here is the other way i tried. but no luck

var scriptElement = document.createElement('script');
            scriptElement.innerHTML = $('#tbodyId').last().html();
            document.getElementById('#tbodyId').appendChild(scriptElement);

any help would be appreciated. Thanks!!

Hi I want to add tool-tip to kendo grid row

Hi I want to add tool-tip to kendo grid row I used following code but it is not working........

<div id="clientsDb">
        @(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.CustomerViewModel>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.Bound(c => c.ContactName).Width(140).HtmlAttributes(new { title = "##" });
                columns.Bound(c => c.ContactTitle).Width(190);
                columns.Bound(c => c.CompanyName);
                columns.Bound(c => c.Country).Width(110);
            })
            .HtmlAttributes(new { style = "height: 380px;" })
            .Scrollable()
            .Groupable()
            .Sortable()
            .Pageable(pageable => pageable
                .Refresh(true)
                .PageSizes(true)
                .ButtonCount(5))
            .DataSource(dataSource => dataSource
                .Ajax()
                .Read(read => read.Action("Customers_Read", "Grid"))
            )
        )
    </div>

This part is used for tool tip

 @(Html.Kendo().Tooltip()
                    .For("#clientsDb")
                        .Filter("grid")
                .Position(TooltipPosition.Top)
                .Width(120)
        )

How to design a editor field in asp.net mvc 3 to display only the textbox?

As i have not created a field for the current date in a database table, and not also in model class also, but i want to display only the view of that field?

<div class="editor-label">
  @Html.Label("Date")
</div>                     
<div class="editor-field">
  //here is the problem what to do??
  @Html.EditorFor(m => m.????)
  @Html.ValidationMessageFor(model => model.???)
</div>

mercredi 19 août 2015

Parse JSON output in asp.net MVC 3

I want to parse JSON string in C# asp.net mVC3 but not getting idea of how to parse my json string. my JSON String is like that:

{"dept":"HR","data":[{"height":5.5,"weight":55.5},{"height":5.4,"weight":59.5},{"height":5.3,"weight":67.7},{"height":5.1,"weight":45.5}]}

Code:

var allData = { dept: deptname, data: arr};
var allDataJson = JSON.stringify(allData);
$.ajax({
                url: '<%=Url.Action("funx","Controller")%>',
                data: { DJson: allDataJson },
                async: false,
                cache: false,
                type: 'POST',
                success: function (data) {
                    alert("success data: "+data);
                }

}); 

public String funx(string DJson)
{
     System.Diagnostics.Debug.WriteLine("Returned Json String:" + DJson);

     // var yourObject = new JavaScriptSerializer().Deserialize(DJson);
     return "successfull";
}

I am new to asp.net. I want to parse the string and save it in database.

Using MVC 4 extensions in MVC 3

I want to use Html.LabelFor() extension of Asp. Net MVC 4 to add html attributes to a Label. I'm using MVC 3. My question is: Can I simple upgrade my system.web.mvc dll?(any problem with this?...) OR it will be a problem in deploy?

What is the purposes of exe files in the MVC5 projects?

In MVC5 Project there are 3 exe files: enter image description here

My web-hosting provider is not letting me to publish exe files, and he told me to delete them.

During web-deploy I remove selection for this 3 files and publish the rest of the project.

When the publishing process finish and I try to access my website I got the error message that the csc.exe is missing :)

Can I do something to not publish exe files and also my website to run as expected?

Edit - I changed MVC4 with MVC5!

Could not load file or assembly 'System.Web.Mvc' in MVC3

I have installed .net Framework 4.5.2 and MVC3 on Windows 2008 web server. I tried deploying application in IIS on server. After browsing the UI, I am getting below. Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Complete error is:

Server Error in '/' Application.

Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Mvc' could not be loaded.

WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[FileLoadException: Could not load file or assembly 'System.Web.Mvc' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

[FileLoadException: Could not load file or assembly 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)] System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0 System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16 System.Reflection.Assembly.Load(String assemblyString) +28 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +736 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217 System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170 System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +284 System.Web.Compilation.BuildManager.ExecutePreAppStart() +153 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +521

[HttpException (0x80004005): Could not load file or assembly 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9930568 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254