lundi 30 mai 2016

How to display error message under right element in the UI

I have these two view model properties that has these validation attributes.

[CardTypeValidation(ErrorMessage = "Card type is mandatory")]
public CCardType CardType { get; set; }

[CardNumberValidation("CardType", ErrorMessage = "Card type is not a right match for the card number provided")]
public string CardNumber { get; set; }

Now my problem is all validation works fine but the error message "Card type is not a right match for the card number provided" is displayed underneath the Card number textbox. (Which is right below the Card Type dropdown).

My tester is after that the message should be displayed under the Card Type dropdown.

If I put this attribute on the Card Type, then it has some wierd exception and not proper validation either. So its just the message instead of getting displayed under the card number, it should display under the card type. How to do that?

Razor MVC 3 Ajax returns 404

I'm trying to do a basic autocomplete via jquery AJAX, using Razor MVC 3 and Visual Studio 2012 (all of which I had never used before) My code is as follows

JS:

$(document).ready(function () {        
    $("#city").keyup(function () {
        var input = $(this).val();
        getCities(input);
    });
});

function getCities(input) {
    var serviceURL = $("#autocompleteURL").val();    
    var url =
        $.ajax({
            type: "POST",
            url: serviceURL,
            data: {
                'guess': input
            },
            success: function (data) {
                alert('OK!!');    
            },
        });
}

Since i learned that it's not possible to use Razor syntax in a JS file, I'm getting the value from the view via a hidden input, like:

<input type="hidden" id="autocompleteURL" value="@Url.Action("AutoCompleteCity", "Controllers/SearchController")" />

Controller:

 public class SearchController: Controller
   {
       public ActionResult AutoCompleteCity(string guess)
        {
            //database stuff here
        }
   }

I don't know if I'm missing something else. Any help will be greatly appreciated. Thanks!

Issues in implementing Windsor Castle at app config level

I have written a dummy program that implements Windsor castle below.But my problem is that i want to write its components in my WEB CONFIG but i don't able to know where to write what..can any one helps me in correcting that

Please correct me writing is App.config level of behaviour i.e to make it configurable??? Dummy Programm:

namespace NnjectFramework
{

    class Program
    {
#region  windsor castle
        interface IFoo
        {
            void test();
            void test2();
        }
        public class Foo: IFoo
        {
            private readonly string _arg1;
            private readonly string _arg2;

            public Foo(string arg1, string arg2)
            {
                _arg1 = arg1;
                _arg2 = arg2;
            }


            public void test()
            {
                Console.WriteLine("Success method 1");
            }
            public void test2()
            {
                Console.WriteLine("Success method 2");
            }
        }
        class Bar
        {
            private Foo bar;

            public Bar(Foo bar)
            {
                this.bar = bar;
            }
        }
        static void Main(string[] args)
        {

            IWindsorContainer container = new WindsorContainer();
            container.Register(Component.For<IFoo>().ImplementedBy<Foo>().LifeStyle.Is(LifestyleType.Transient).Named("AFooNamedFoo"));

            IFoo foo = container.Resolve<Foo>("AFooNamedFoo", new { arg1 = "hello", arg2 = "world" });
            foo.test();
            foo.test2();
            Console.ReadKey();

        }

        #endregion
        }

} 

What i have tried in App.config:

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <components>

    <component id="uniqueId"
    service="Acme.Crm.Services.INotificationService, Acme.Crm"
    type="Acme.Crm.Services.EmailNotificationService, Acme.Crm"
    inspectionBehavior="all|declaredonly|none"
    lifestyle="transient"
    customLifestyleType="type that implements ILifestyleManager"
    componentActivatorType="type that implements IComponentActivator"
    initialPoolSize="2" maxPoolSize="6"></component>
  </components></configuration>

dimanche 29 mai 2016

Many to many value null

Well im trying to do a many to many relationship with my Desafio(challenge) and my Tag model, a challenge can have many tags and a tag can be related to many challenges, i already placed the tags on the view, the problem is when i submit the form, it says that the value is null on this line:

var DesafioTag = new HashSet<int>(
         desafio.Tags.Select(a => a.Id));

i will show how i did:

my models

Tag~

 public class Tag
{
    public int Id { get; set; }
    public string NomeTag { get; set; }
    public string cor { get; set; }
    public virtual ICollection<ApplicationUser> Users { get; set; }
    public virtual ICollection<Desafio> Desafios { get; set; }
}

Desafio(challenge)

 public class Desafio
{
    public int DesafioId { get; set; }

    public string TipoTrabalho { get; set; }

    public virtual ApplicationUser User { get; set; }

    public string ApplicationUserId { get; set; }

    public string Descricao { get; set; }
    public int TipoAvaliacaoId { get; set; }
    public virtual TipoAvaliacao TipoAvaliacao { get; set; }       
    public decimal valor { get; set; }
    public int Visualizacoes { get; set; }
    public DateTime DataCriacao { get; set; }
    public decimal lat { get; set; }
    public decimal lon { get; set; }
    public int IdSolucaoVencedora { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }

}

then i have 2 viewmodels to display the data in the view

DesafioCreate

public class DesafioCreate
{
    public string Desafio { get; set; }
    public string Descricao { get; set; }
    public decimal ValorMonetario { get; set; }
    public decimal lat { get; set; }
    public decimal lon { get; set; }
    public ICollection<TagDesafio> TagDesafio { get; set; }
}

 public class TagDesafio
{
    public int TagId { get; set; }
    public string Nome { get; set; }
    public bool Seleccionado { get; set; }
}

i already did something with many to many relationships to edit, and i did it, but in a create method it doesnt work, i feel that has something to do with my challenge, cause im trying to associate tags with a challenge that doesnt exist, but i dont know if the cause is that, here is the post code that i think is the main problem here

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(DesafioCreate model, string[] selectedTag,HttpPostedFileBase file)
    {
        TipoAvaliacao TipoAvaliacao = db.TiposAvaliacao.Where(i => i.TipoAvaliacaoId == 1).FirstOrDefault();

        if (ModelState.IsValid)
        {
            Desafio desafio = new Desafio();
            desafio.lat = model.lat;
            desafio.lon = model.lon;
            desafio.TipoTrabalho = model.Desafio;
            desafio.Descricao = model.Descricao;
            desafio.DataCriacao = DateTime.Now;
            desafio.TipoAvaliacao = TipoAvaliacao;
            desafio.valor = 22;
            desafio.Visualizacoes = 34;
            desafio.ApplicationUserId = User.Identity.GetUserId();


            var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Anexos"), fileName);
                    var anexo = new Anexo();
                    anexo.Caminho = path;
                    anexo.NomeFicheiro = fileName;
                    anexo.DesafioId = desafio.DesafioId;

                db.Desafios.Add(desafio);

            atualizarTagsDesafio(desafio, selectedTag);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        preencherTagDesafio();
        return View(model);
    }

    private void atualizarTagsDesafio(Desafio desafio,


string[] selectedTag)
        {
            if (selectedTag == null)
            {
                desafio.Tags = new List<Tag>();
                return;
            }
            var selectedAutoresHS = new HashSet<string>(selectedTag);
            var DesafioTag = new HashSet<int>( // line that cause the error
             desafio.Tags.Select(a => a.Id));  // line that cause the error
            var Tags = db.Tags;
            foreach (var tag in Tags)
            {
                if (selectedAutoresHS.Contains(tag.Id.ToString()))
                {
                    if (!DesafioTag.Contains(tag.Id))
                    {
                        desafio.Tags.Add(tag);
                    }
                }
                else {

                    if (DesafioTag.Contains(tag.Id))
                    {
                        desafio.Tags.Remove(tag);
                    }
                }
            }
        }

if soemeone can give me a hand, im a beginner doing this relationships, and i cant find the problem.

Ps: Sorry for my bad english

samedi 28 mai 2016

HtmlHelper

I am trying to add pagination to my website and followed this guide: http://ift.tt/1qT0DfZ

My Controller looks like this:

using PagedList;
using PagedList.Mvc;

public ActionResult Content(int? page)
{
   int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
   Other code here...
   return View(model.ToPagedList(currentPageIndex, 10));
}

And my View looks like this:

@using PagedList;
@using PagedList.Mvc;
@model IPagedList<Prj.Models.ContentModels>

@foreach (var content in Model)
{
   Table code here...
}
<div class="pager">
   @Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount)
</div>

The problem is however that the @Html.Pager part doesn't seem to work. I get the following error:

'HtmlHelper<IPager<Models>>' does not contain a defintion for 'Pager' and no extension method 'Pager' accepts a first argument of type 'HtmlHelper<IPageList<Models>>' could be found (are you missing a using directive or an assembly reference?)

I have installed both PageList and PageList.Mvc via NuGet.

MVC3 pass exception from controller to view

want to print the exception on cshtml page, but unbale to get where to use this

 @Html.ValidationSummary()
      <form method="post" action="AddUser">
   </form>

vendredi 27 mai 2016

Why does Html.CheckBoxFor output a 'false' as the value where a Html.HiddenFor outputs a 'False' (lower vs proper case)?

I'm not sure if it is intended behavior or not but when I use a @Html.CheckBoxFor(x => x.CheckBox1) it will output two input fields (one of which is false and one is true because html doesn't post back false checkboxes). But the actual html rendered is:

<input id="CheckBox1" name="CheckBox1" type="checkbox" value="true"> <input name="CheckBox1" type="hidden" value="false">

But when I use a @Html.HiddenFor(x => x.CheckBox2) the output is:

<input id="CheckBox2" name="CheckBox2" type="hidden" value="True">

Note the 'true' and the 'True'. When the out of the box jquery.validate.js tries to use the equalTo function it will never be equal to each other because 'true' !== 'True'.

To get around this I can modify the equalTo method to ignore case when comparing checkbox values but I was just curious if this is a bug with the MVC framework or this was intended behavior?

Here is a fiddle reproducing the issue (view source on the output to view the html): http://ift.tt/20LCvYV

Edit 1: I have found in the CheckBoxFor source that it is passing a lower case 'true' when building the Checkbox. The question still remains, why lower case instead of proper case. http://ift.tt/25qJopr Line 96 of the source.

mercredi 25 mai 2016

dropdownlist show resources culture asp.net mvc

i have done it using html helper razor and work is properly.Here is my code snippet

    <a href="@Url.Action("data","Home", new { lang = "en"})">English</a> |
    <a href="@Url.Action("arabic","language", new { lang = "ar"})">Arabic</a>
    <a href="@Url.Action("  French ","language", new { lang = "fr"})">  French </a>

but i need converting into dropdownlist How it's??

"String was not recognized as a valid DateTime in Asp.net

string JDate = "21/01/2016 3:47 PM";

when i convert jDate to DateTime, An error Occured

DateTime journeyDate = DateTime.ParseExact(JDate,"MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);

String was not recognized as a valid DateTime.

issue regarding re direct from aspx page to mvc

I have used PostBackUrl(url) to re direct from aspx to mvc page . Because my aspx and mvc projects are on different domain.

its getting redirected but I have to refresh the page to go to "url".

Please give me some solution on how to re direct from aspx to mvc page which are in different domain

write Rhino Mock Test cases for Web api

HI have created a WEBAPI below. i am trying to write rhino Mocks for below API i have tried a lot but everytime i failed

WEBAPI Code

[Route("api/{Home}/{Username}/{Password}")]
        public HttpResponseMessage Get(string Username, string Password)

        {
            HttpResponseMessage response;
            var display = Userloginvalues().Where(m => m.UserName == Username && m.Password == Password).FirstOrDefault();
            if (display != null)
            {
                response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent("xxxx.", Encoding.Unicode);
            }
            else
            {
                response = Request.CreateResponse(HttpStatusCode.NotFound);
                response.Content = new StringContent("xxxx", Encoding.Unicode);
            }
            return response;

        }
        public static List<LoginModel> Userloginvalues()
        {
            List<LoginModel> objModel = new List<LoginModel>();
            objModel.Add(new LoginModel { UserName = "test", Password = "test" });
            return objModel;
        }

RHIN MOCKS i tried below but dont know how to proceed

MockRepository mocks = new MockRepository();
            WebApplication1.Models.ILoginRepository login = mocks.Stub<WebApplication1.Models.ILoginRepository>();
            HttpResponseMessage _respone;
            _respone = login.Get("test", "test");

mardi 24 mai 2016

How to enable jquery to insert multiple row to database which include @Html.DropDownListFor in the table

I'm new to mvc and jquery
When I use dropdownlist in this table, jquery code never work
this table without DropDownList, code of jquery work perfect
so I must be edit in jquery code to work perfect
this is my code

<div><a href="#" id="addNew">Add New</a></div>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <th>color</th>
        <th>WindowType</th>
        <th>height</th>
        <th>width</th>
        <th></th>
    </tr>
    @if (Model != null && Model.Count > 0)
    {
        int j = 0;
        foreach (var item in Model)
        {
            <tr style="border:1px solid black">
                <td>@Html.DropDownListFor(m => m[j].Color, (SelectList)ViewBag.color)</td>
                <td>@Html.DropDownListFor(m => m[j].WindowType, (SelectList)ViewBag.WindowType)</td>
                <td>@Html.TextBoxFor(m => m[j].height, new { @class = "form-control" })</td>
                <td>@Html.TextBoxFor(m => m[j].width, new { @class = "form-control" })</td>
                <td>
                    @if (j > 0)
                    {
                        <a href="#" class="remove">Remove</a>
                    }
                </td>
            </tr>
                    j++;
        }
    }
</table>
    <input type="submit" value="Save Bulk Data" />

this in code of jquery

@section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
    <script language="javascript">
        $(document).ready(function () {

            //1. Add new row
            $("#addNew").click(function (e) {
                e.preventDefault();
                var $tableBody = $("#dataTable");
                var $trLast = $tableBody.find("tr:last");
                var $trNew = $trLast.clone();

                var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
                $trNew.find("td:last").html('<a href="#" class="remove">Remove</a>');
                $.each($trNew.find(':input'), function (i, val) {
                    // Replaced Name
                    var oldN = $(this).attr('name');
                    var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
                    $(this).attr('name', newN);
                    //Replaced value
                    var type = $(this).attr('type');
                    if (type.toLowerCase() == "text") {
                        $(this).attr('value', '');
                    }

                    // If you have another Type then replace with default value
                    $(this).removeClass("input-validation-error");

                });
                $trLast.after($trNew);

                // Re-assign Validation
                var form = $("form")
                    .removeData("validator")
                    .removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse(form);
            });

            // 2. Remove
            $('a.remove').live("click", function (e) {
                e.preventDefault();
                $(this).parent().parent().remove();
            });

        });
    </script>
}

Can some body help me?

One to Many with Circular Relationship

I'm trying to build a structure that has many domains and menus. All Menus are related to a domain with DomainID, So each domain can manage owns.

Also, domain owners can select where to show to menu, it may be on Heade or on Footer areas.

Here is my models

public class Domain
    {
        [Key]
        public int DomainID { get; set; }
        public string Name { get; set; }
        public string Template { get; set; }
        public string BookingType { get; set; }

        public int? HeaderMenuID { get; set; }
        public int? FooterMenuID { get; set; }

        public virtual Menu HeaderMenu {get;set;}
        public virtual Menu FooterMenu { get; set; }

        public virtual List<DomainTranslation> DomainTranslations { get; set; }
        public virtual List<Language> Languages { get; set; }
        public virtual List<User> Users { get; set; }
        public virtual List<Form> Forms { get; set; }
        public virtual List<Car> Cars { get; set; }
        public virtual List<Menu> Menus { get; set; }
    }



public class Menu
{
    [Key]
    public int MenuID { get; set; }
    public int DomainID { get; set; }
    public int? ParentMenuID { get; set; }

    [ForeignKey("ParentMenuID")]
    public virtual Menu Parent { get; set; }


    public virtual List<MenuTranslation> MenuTranslations { get; set; }
    public virtual Domain Domain { get; set; }
}

When I update-database expected fileds on Menu database is :

[MenuID]
[DomainID]
[ParentMenuID]

But it is populating as

[MenuID]
[DomainID]
[ParentMenuID]
[Domain_DomainID]
[Domain_DomainID1]

So, there is Domain_DomainID and DomainDomainID1 fields are populating mysteriously.

What I am doing wrong?

lundi 23 mai 2016

Moving a file in microsoft webmatrix

As a project I'm working in microsoft webmatrix. The problem I had was my files were saving to My WebSites directory and not compiling so I changed the virtual path in IISExpress application.hostconfig to www.root. I was then able to compile lab15_1.cshtml and run it in the browser. I can see it in the solution explorer in visual studio 2010. Then I created lab15_2.cshtml but it won't run in the browser because it is in My Website directory. I don't know how I messed up, but I need to know how to move files to the solution explorer. I want to move lab15_2.cshtml to www.root but I don't know how. I'm thinking I should be able move it to the solution explorer to the website where lab15_1.cshtml is located. Does anybody know how I can do that? Much appreciation. Thank you in advance.

What this query string values means UNION SELECT cAsT(0x2d78312d512d as char)

I am getting the query string value in my Log table like

PLayVideo.aspx?webinarid=9111111 UNION SELECT cAsT(0x2d78312d512d as char),//cAsT(0x2d78322d512d as char),//cAsT(0x2d78332d512d as char),//cAsT(0x2d78342d512d as char),//cAsT(0x2d78352d512d as char),//cAsT(0x2d78362d512d as char),//cAsT(0x2d78372d512d as char),//cAsT(0x2d78382d512d as char),//cAsT(0x2d78392d512d as char),//cAsT(0x2d7831302d512d as char),//cAsT(0x2d7831312d512d as char),//cAsT(0x2d7831322d512d as char),//cAsT(0x2d7831332d512d as char),//cAsT(0x2d7831342d512d as char),//cAsT(0x2d7831352d512d as char)

Anyone have the idea about it ?

samedi 21 mai 2016

Populating HTML Table from JSON API in ASP.NET

So I am wanting to populate a table with items coming from a self made API. The API is working fine (showing / putting and deleting items,...), but I've failed to populate the existing table with the items.

What I'm using: - ASP.NET (MVC 5) - Entity Framework - JSON

What I have so far: url => /api/Film/ image I am asking this in a new thread since the solution should be working normally, I can't be bothered to learn this is in another method. I hope this won't be a problem.

My code:

Overview view:

<h3>Films</h3>
<table id="Films" border="1">
    <tr>
        <th>ID</th>
        <th>Titel</th>
        <th>Regisseur</th>
        <th>Ranking</th>
    </tr>
</table>

script:

 $(document).ready(function () {
            $.ajax({
                url: '/api/Film',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    $.each(data, function (key, item) {
                        $('#Films').append("<tr><td>" + item.Id + "</td>" + "<td>" + item.Titel + "</td>" + "<td>" + item.Regisseur + "</td>" + "<td>" + item.Ranking + "</td><td><a href=\"#\" onclick=\"deleteFilm(" + item.Id + ")\">delete</a></tr>");
                    });
                }
            });

the (api)controller

// GET api/Film
public IEnumerable<Film> GetFilms()
{
    return db.Films.AsEnumerable();
}

What seems to be the problem in my code?

jeudi 19 mai 2016

When I Use VS2015 and Develop MVC3 Program, there have been some strange problems

There is a MVC3 program developed and compile using VS2012. It's OK and deployed is also OK.

But when I use VS2015 compile,http://ift.tt/1Ttd6T1,not error,just warning。

but when deploy,It can't run.The error http://ift.tt/20dbnBP.The error text is

[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\7c2060f6\6145b34e\assembly\dl3\9036b7c7\fc8023c0_73fecb01\System.Web.WebPages.Razor.DLL'.

So,I Know I should be good to learn English, but now what should I do?

How to Enable HtmlHelper.ClientValidationEnabled for Partial View Only

i need to know, is it possible to enable client side validation for specific Partial View only? I've tried placing the code as below in my partial view, but it still validate my parent view. any ideas?

Thanks

--sample of my parent view----

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

{

 @Html.AntiForgeryToken()

 @Html.Partial("_FPdetails")

 @Html.Partial("_RawMaterialTable")

 @Html.Partial("_CreateNewRawMaterial")   

}

--partial view (_CreateNewRawMaterial)--

@model MyCOOEntity.CostAnalysisModel.FinishProductCompleteForm

@{    
    HtmlHelper.ClientValidationEnabled = true;
}

<div>
--codes-
</div>

How to do to display timing for the result's items found in MVC3(C#)?

Please someone teach me how to display timing (seconds) for the search result in MVC3(C#). I searched but don't know how to do or what function I have to use on MVC3. I attached image file that I would like to display. Here the image file.

Thanks for your help.

Using SDL MiniFuzz on MVC App

I'm currently working on a project where we are required to do Fuzz Testing, though I'm not entirely sure if you can or not on MVC. I was pointed to Microsoft's SDL MiniFuzz app for doing my Fuzz Testing, but quickly realized it accepts .exe, which I do not have.

My question is can MiniFuzz do any testing on a Web App? And if not, what is out there to do Fuzz Testing on Web Apps?

mercredi 18 mai 2016

Why does Response.StatusCode = (int)HttpStatusCode.NotFound give me the generic error handler?

I catch and redirect 404 errors to an Error controller \ views with the following code.

        Response.Clear();
        Server.ClearError();
        var routeData = new RouteData();
        routeData.Values["controller"] = "Error";
        routeData.Values["action"] = "HttpError";
        routeData.Values["exception"] = exception;          

        Response.StatusCode = 500;
        //if http 404 redirect to http404 action
        if (httpException != null)
        {
            Response.StatusCode = httpException.GetHttpCode();
            switch (Response.StatusCode)
            {
                case 404:
                    routeData.Values["action"] = "Http404";
                    break;
            }
        }

In the error controller if I set Response.StatusCode = (int)HttpStatusCode.NotFound I get the generic error handler, not the view I returned. This only seems to happen in production. Any ideas why?

    [AllowAnonymous]
    public ActionResult Http404()
    {
        //this line causes generic error handler
        Response.StatusCode = (int)HttpStatusCode.NotFound;

        var viewModel = new ErrorViewModel
        {
            Description = "Hmm, the page you're looking for can't be found"
        };

        return View("Error", viewModel);
    }

How to find Key OutputCacheAttribute.ChildActionCache in mvc 3?

I have some problem:

This my action code:

[OutputCache(Duration = 3600, VaryByParam = "session")]
public PartialViewResult MiniAccountProfile(string session)
{
     //My business

     return PartialView("myPratialView", model);
}

In my PartialView, i have define enum "ActionCacheEnum.MiniAccountProfileAction" string:

<div class="menu-photo" data-cache="@ActionCacheEnum.MiniAccountProfileAction.ToString()" onclick="location.href = '/Extensions/User/Settings'">

And code find OutputCacheAttribute:

var item = OutputCacheAttribute.ChildActionCache.FirstOrDefault(x => x.Value.ToString().Contains(enumIndex));
    if (OutputCacheAttribute.ChildActionCache.Any())
    {     
         OutputCacheAttribute.ChildActionCache.Remove(ActionCacheEnum.MiniAccountProfileAction);
    }

This my idea. But i think performance its not good, because it must find into big string.

My question. How to find key of OutputCacheAttribute.ChildActionCache by ActionResult using its?

I try to using Response.RemoveOutputCacheItem, but it not work, and i read more topic example enter link description here. And They say: "Currently what you are trying to achieve is not possible in ASP.NET MVC 3. If you want to use donut output caching I would recommend you the following article. Hopefully this functionality will be added in ASP.NET MVC 4."

Thanks for helping me.

Slash in the ActionName attribute for MVC

Is it possible to have a slash in the ActionName attribute in ASP MVC?

e.g. I would like a paths

MyController/MyAction1
MyController/MyAction2/A
MyController/MyAction2/B
MyController/MyAction3

The reason for this is it mimics the navigation a user would use. But if I try to add the following to MyController it doesn't work.

[ActionName("MyAction2/A")]
public ActionResults A() {...}

Obviously without the attribute it wouldn't work either.

I've tried changing my RouteConfig.cs to

routes.MapRoute(
    name: "MyController",
    url: "MyController/MyAction2/{action}",
    defaults: new { controller = "MyController", action = "Index" }
);

But this affects all MyController paths. How can I get either a slash in the action name, or have the route config 'override' only come in to play when the action is MyAction2?

asp.net mvc3 idle time out redirect to login automatically and store log out time

My application is in asp.net MVC3 version and i am stuck with the following Problem:


Scenario If user is idle for More than 2 min than he/she should be get log out and also at that moment I have to log his/her time (when their session got ended) to the database.


Problem: As I am storing user info in the session.So once user is redirected to login page their log out time need to be logged also need to consider scenario for multiple browser tabs opened at a moment.

Oauth Authentication

I have implemented OAuth token based authentication for my web api. In Oauth it used Entity framework for handling membership but I want to remove Entity framework and wish to implement my own membership. Is it possible to use OAuth without entity framework.

Regards, Ganesh

url of webapi, how to configure in mvc

I Have a url to a webapi, like this:

http://ift.tt/1TYZNbO"

and in the mvc project I have this files:

public class RouteConfig
    {

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "DefaultApi",
                url: "DefaultApi/{action}/{id}",
                defaults: new { controller = "Guestbook", action = "Index", id = UrlParameter.Optional, PageID = 1067 }
            );

        }
    }

 public class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "webapi/NavToDW",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        }    
    }

and the Global.asax file:

public class Global : System.Web.HttpApplication
    {
        public void Application_Start(object sender, EventArgs e)
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.RazorViewEngine());
            ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.WebFormViewEngine());
            // Fires when the application is started
            Dynamicweb.Frontend.GlobalAsaxHandler.Application_Start(sender, e);

            GlobalConfiguration.Configuration.EnsureInitialized();
        }

        public void Session_Start(object sender, EventArgs e)
        {
            // Fires when the session is started
            Dynamicweb.Frontend.GlobalAsaxHandler.Session_Start(sender, e);
        }

        public void Application_BeginRequest(object sender, EventArgs e)
        {
            // Fires at the beginning of each request
            //GlobalAsax.Application_BeginRequest(sender, e);
        }

        public void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            // Fires upon attempting to authenticate the use
            Dynamicweb.Frontend.GlobalAsaxHandler.Application_AuthenticateRequest(sender, e);
        }

        public void Application_Error(object sender, EventArgs e)
        {
            // Fires when an error occurs
            Dynamicweb.Frontend.GlobalAsaxHandler.Application_Error(sender, e);
        }

        public void Session_End(object sender, EventArgs e)
        {
            // Fires when the session ends
            Dynamicweb.Frontend.GlobalAsaxHandler.Session_End(sender, e);
        }

        public void Application_End(object sender, EventArgs e)
        {
            // Fires when the application ends
            Dynamicweb.Frontend.GlobalAsaxHandler.Application_End(sender, e);
        }

        public void Application_OnPreRequestHandlerExecute(object sender, EventArgs e)
        {
            Dynamicweb.Frontend.GlobalAsaxHandler.Application_OnPreRequestHandlerExecute(sender, e);
        }
    }

So I can can connect. But I cant go to the specific link, like this: http://ift.tt/1TYZNbO

the outcome is this:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
bij System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() bij System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) bij System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>

So what I have to change?

Thank you

mardi 17 mai 2016

Can't create component as it has dependencies to be satisfied. Parameter which was not provided

I have just started using Windsor to resolve dependency. But i am getting below error while passing string value in my Controller.I checked couple of similar Windsor Post but no luck.

public class HomeController : Controller
{
    public readonly String _A = string.Empty;
    public HomeController(string A)
    {
        this._A = A;        
    }
}

Installer

public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .BasedOn<IController>()
            .LifestyleTransient());
    } 

WindsorControllerFactory

public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;

        public WindsorControllerFactory(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public override void ReleaseController(IController controller)
        {
            kernel.ReleaseComponent(controller);
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }
            return (IController)kernel.Resolve(controllerType);
        }
    }

Do i need to wrap 'A' inside a class and resolve it's respective Interface ?

Code generated by RazorGenerator not executed, script code still is

So I installed RazorGenerator with nuGet and added the VS extension (thanks to Visual Studio cannot find custom tool RazorGenerator).

Just to try it out on my existing mvc app, I changed the custom tool to RazorGenerator on one of the views, and generated the code with the right-click option "Run Custom Tool". The code was indeed created.

I then build the entire app and tried running it, setting a break point in both the old razor script and the new pre-compiled code. Much to my surprise, it was still running the old script code, not the new. Am I missing a step somewhere to switch over execution to the new code. The documentation is a little skimpy, but you would think something crucial like this would have been mentioned if needed. I know it calls the bootstrap code in App_Start using WebActivatorEx.PostApplicationStartMethod(), or at least it did so once, doesn't seem to do it on every debug start though, not even after an iisreset. If I try to delete the source razor view the ajax call fails when returning result, so it is obviously not using the precompiled code. Am I missing a step somewhere?

How to add buttons to each row in a dataTable?

I've added a table to my which dynamically creates the table columns and rows. What I'm trying to do now is add an Edit and Delete button to each row in that table.

In order to achieve that I tried placing two td's containing the buttons wihthin the for..each loop that creates the table rows.:

@foreach (var cell in row.ItemArray) {
  <td style="word-wrap:break-word;font-size:11px">@cell.ToString()</td>
  <td><a class="btn-success">Edit</a></td>
  <td><a class="btn-danger">Delete</a></td>
}

But this add two buttons to each cell in every row which is not the intended outcome.

Question:

How can buttons be dynamically created for each row in a data table?

Razr markup for table:

 <table id="escalation" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            @foreach (System.Data.DataColumn col in Model.Columns)
            {
                <th style="font-size: 12px; border-right: 1px solid #7591ac; ">@col.Caption</th>

            }
        </tr>
    </thead>
    <tbody>
        @foreach (System.Data.DataRow row in Model.Rows)
        {
            <tr>
                @foreach (var cell in row.ItemArray)
                {
                    <td style="word-wrap:break-word;font-size:11px">@cell.ToString()</td>
                    <td><a class="btn-success">Edit</a></td>
                    <td><a class="btn-danger">Delete</a></td>
                }

            </tr>
        } 
    </tbody>
</table>

ChildActionOnly attribute not working

Though i invoke action method from actionlink present in the view.Its giving me error "action 'Demo' is accessible only by a child request".

lundi 16 mai 2016

WebActivatorEx.PostApplicationStartMethod() not called at startup

Trying to attach a WebActivatorEx.PostApplicationStartMethod() to an existing MVC 3 application, in particular RazorGenerator.

[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(TiPSViewWeb.RazorGeneratorMvcStart), "Start")]

namespace TiPSViewWeb {
    public static class RazorGeneratorMvcStart {
        public static void Start() {
            var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly) {
                UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
            };

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages. 
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
        }
    }
}

However this code is never executed during startup. I tried creating a new basic mvc application and installed Razor Generator into it, and the application is breaking nicely in the Start(). Am I missing a step here in order to make the app server call the right function? Is there anything that might be overshadowing that call?

I have this in Application_Start():

protected void Application_Start() { RouteTable.Routes.Ignore("{resource}.axd"); AreaRegistration.RegisterAllAreas();

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

InitSquishIt();

Application["ReportTasks"] = new Dictionary<long, Thread>();
Application["ReportTokens"] = new Dictionary<long, string>();

}

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

}


//-----------------------------------------------------------------------------------
// Name:        RegisterRoutes
// Purpose:     Register the routes for the site.
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("admin/http://ift.tt/1rQjxp0}");
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
    routes.IgnoreRoute("Scripts/{folder}/{resource}.js.axd/{*pathInfo}");
    routes.IgnoreRoute("XML/{type}/{folder}/{resource}.xml.axd/{*pathInfo}");

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

Security Exception in nopCommerce with Full Trust set

I am using nopCommerce 3.70 on Godaddy's shared Hosting. I have had this website up and running for the last month or so, no problem until just the other day. All of a sudden I am getting a security exception error, that would normally tell me that my site is not set to "Full Trust"; however, it is and I even called Godaddy to have them verify that it was actually set. I can not for the life of me figure out why this site will not work and I even re-downloaded, unblocked and republished this site (everything except the App_Data folder, don't want to loose the db). Same error:

[SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.] System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) +34
System.Security.CodeAccessPermission.Demand() +46
System.Web.HttpContext.System.IServiceProvider.GetService(Type service) +54 System.Web.HttpContextWrapper.GetService(Type serviceType) +13
System.Web.WebPages.UrlRewriterHelper.IsUrlRewriterTurnedOn(HttpContextBase httpContext) +108

in debug mode it says the issue is at line 31

Line 29: Line 30: Line 31: @Html.Widget("header_links_before") Line 32: @T("HomePage") Line 33:
@T("ContactUs")

Has anyone else ever encountered this issue? Any ideas about what else I can try to fix this?

Also, after about 4 calls with GoDaddy they are saying that the website is trying to perform a task that either the website itself doesn't allow or the server wont allow, because it's shared hosting.

Any help with this would be so greatly appreciated. Thank you in advance.

Display multiple div after Http post ASP.NET MVC3 RazorView

I am a new to ASP.NET MVC, I had been working on ASP.NET Webform. I have couple of questions with respect to design in ASP.NET MVC. [Note I am working on ASP.NET MVC3 Razor View Engine].

SCENARIO

I am creating a search panel. So When the search is submit, it search for different information. Example: An account search. So in search I am providing information and the search would result, Account details (different panel), Account Balance (different panel), all activities belongs to that account (seperate panel)

  1. How should I display the three panels after the search is submitted?
  2. Displaying activities search result would have the feature to edit each item as well. So should I keep the activities result in partial view or in the same view?
  3. My two panel (Account details and account balance) would always be displayed after the search is performed. But they should be hidden before the search is performed. But for activities if the result is null, display a message for "No result found". How should I implement this feature?

I know in Webform it's easy to make visible panel if the search is conducted and display the information. But how to achieve in ASP.NET MVC, kind a new for me.

Any help would be really appreciated.

dimanche 15 mai 2016

passing List object that created in controller to Index view

I have a problem to create a advance search in mvc, because I am new in mvc so I made some mistake in code in my question (but I made a lot of complicated sit in asp.net in vb or c#), I fixed my code with Mark's link (http://ift.tt/1ySIobw) , because some friend answer to my first wrong question that was solved by my self and it was confused I decided to ask new situation of my problem.

Actually now my search is working probably, I summarize the code as below:

My search view is:

@model IEnumerable<WomenNew.Models.News_>
@{
    ViewBag.Title = "AdvanceSearch_";
}
<h2>AdvanceSearch_</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.TextBox("Details", "this is value")
     <input type="submit" value="Search" />
}

In controller this view call it's method:

    [HttpPost]
    public ActionResult AdvanceSearch_(string Details)
    {
        //List<News_> news_ = new List<News_>();
        if (Deatails != null)
        {
            newsList = db.News_.Where(x => x.Deatails.Contains(Details)).ToList();
            return RedirectToAction("Index", "News_");
        }
        else
            return View("AdvanceSearch_");
    }

I had to define a public static variable because I don't know the correct way and I ask this question to know how the correct is.

public static List<News_> newsList = null;

And in my ActionResult Index I add a condition to know either newesList is null otherwise I pass the ListObject to Index view and sear work fine

    [HttpGet]
    public ActionResult Index(string searchBy, string search )
    {
        if(newsList != null)
        {
            return View(newsList);
        }
      .....
     }

I tried to not define public Variable but with passing between AdvanceSearch_ and Index the variable became null even ViewBag I checked it became null, I thought in protected override void Dispose(bool disposing)

method this is happened but I checked in another point it changed to null One friend told

A public static field is a single memory location available to every user of the application. Every user shares the same value.

I appreciate If anybody con help me how I can pass a List of Object from second block in this question (ActionResut Advance Search) to third block (Index ActionResult) or give me a link of code or a link of Walk trough for search in mvc which shows advance search with more fields. All I found out is a simple search inside the same view. A very kind friend (mgebhard) guide me to use TempData and he gave me a link :this is a tutorial mvc and is very valuable
Thanks a lot
Regards
Tomas

How can I import view and controllers from solution to another using DLL?

I create a view with method in controller in one solution, but my exact probelm is, I need to Import those to another solution, how can I do that using dll's ? and is there another methods to do that?

vendredi 13 mai 2016

Controller Action Method is not getting called when custom routebase class is used

    Following is the Custom RouteBase class 

 public class CustomRoutingBehaviour:RouteBase
        {
            string[] allowedUrl;
            public CustomRoutingBehaviour(string[] url)
            {
                allowedUrl = url;
            }

            public override RouteData GetRouteData(HttpContextBase httpContext)
            {
                RouteData route = null;
                string browsedurl = httpContext.Request.AppRelativeCurrentExecutionFilePath;
                if(allowedUrl.Contains(browsedurl,StringComparer.OrdinalIgnoreCase))
                {
                    route = new RouteData(this,new MvcRouteHandler());
                    route.Values.Add("controller","CustomiziedController");
                    route.Values.Add("action","Index");
                    route.Values.Add("BrowsedURL",browsedurl);

                }

            return route;
            }

            public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
            {
                return null;
            }
        }

Following is the routing configuration: routes.Add(new CustomRoutingBehaviour(new string[] { "~/Customizied/Index", "~/Customizied/Index1" }));

jeudi 12 mai 2016

What is the difference between asp.net mvc 3 vs 4 vs 5 vs 6?

Is there any major difference between asp.net mvc 3 vs 4 vs 5 vs 6 .I start a application with MVC 4 . but my friend saying it is to much better if i select mvc 6 .

just few query :

1) is it faster than each other?

2) there have any major change?

how can I use Html.RenderPartial to get value

I have this view

@model WebSite.Models.mymodelModel
@{     ViewBag.Title = "AudioPlayer2"; }
<div>    
    @{Html.RenderAction("AudioPlayer", "mycontroller", new { storyId = 3027, className = "" });}
</div>

the @model comes null all the time SO,how can I use Html.RenderPartial to get the @model.storyId which I can get from controller as

 List<str> rtn = new List<str>();
   rtn = GetLatestEpisodes(DateTime.Now.AddMonths(-3).ToString(), DateTime.Now.ToString(), 0, 1);

storyId is the rtn.stroryId

mercredi 11 mai 2016

How to invoke a javascript function after a View or PartialView is rendered?

I am using MVC to render a View. The view has a single DIV element and a SCRIPT element. The SCRIPT element has a simple alert('hello world').

When the view is rendered I expected to see the alert popup. Unfortunately this is NOT the case.

What can be done to invoke a script function after a View is rendered?

Is it possible to use MVC 6 in Visual studio 2012?

I have a project developed in MVC 6 into Visual Studio 2015. I want to configure it in my system.
My system has Visual Studio 2012.
I want to know, Is it possible to run MVC 6 project into Visual Studio 2012?
I searched a lot but I did not get satisfactory answer.Can anyone guid me regarding this?
When I tried to buil this project in my system, I got the error i.e. "The Web project 'ABC' requires missing web components to run with Visual Studio."

Working on templates for coloums in kendo grid

I have been trying to use if and else in a template of one of the field in kendoGrid.I have two fields "StatusDesc" and "newStatusDesc". I want show one of the value as an anchor tag. That is displaying fine but if you notice onclick defined for anchor tag,it has one of the field from the grid itself because it has to open a another page but when i click on the anchor tag, console of my browser shows:

uncaught ReferenceError: WEW6101 is not defined

Actually if I check firebug, it shows below value set to my anchor tag parameter which is correct but I am not able to call the function "WEW6101"

onclick='openStatusReload(WEW6101)



  $("#Grid").kendoGrid({
        dataSource: TUEDataSource,
        autoBind: false,
        scrollable: false,
        sortable: {
            allowUnsort: false
        },
        //filterable: { mode: "row", style: "max-width:100px;" },
        //groupable: true,
        pageable: {
            refresh: true,
            buttonCount: 5,
            pageSizes: 5
        },
        dataBound: gridDataBound,
        columns:
            [
                { field: "newStatusDesc", hidden: true },
            { field: "StatusDate", title: "Status Date", width: 200, format: "{0:MM/dd/yyyy}", filterable: { cell: { showOperators: false, suggestionOperator: "contains" } } },
            { field: "Status", title: "Status", width: 150, filterable: { cell: { showOperators: true } } },
            { field: "LimitedDate", title: "Expiration Date", format: "{0:MM/dd/yyyy}", width: 150, filterable: { cell: { showOperators: true } } },
            {
                field: "StatusDesc", title: "Comments", width: 150,
                template: "#if(StatusDesc == '' && newStatusDesc!='' && newStatusDesc!= null  ) {#<a href='javascript:void(0)' class='margin-right10' onclick='openStatusReload(#=newStatusDesc#)'> #:newStatusDesc#</a>#} else{##:StatusDesc##}#", filterable: { cell: { showOperators: true } }
                // template: "<a href='javascript:void(0)' class='margin-right10' onclick='openPlayerTUEStatusReload(#=Tue_StatusDesc#)'>#=TueStatusDesc#</a>", filterable: { cell: { showOperators: true } }
            },
            ]
    });

need help in converting to async

I am not able to convert to async action. It says await required

public async Task<JsonResult> Get_Fare_TypeAsync()
            {
                var types = db.Types.Select(e => new { ID = e.Code, Description = e.Description, Value = e.Code, SortOrder = e.SortOrder }).ToList().OrderBy(x => x.SortOrder);


                return Json(types ,JsonRequestBehavior.AllowGet);
            }

Downloading files from MySQL db in asp.net mvc

I am working on a website where i'm storing excel files in blob fields in a mysql db. I need for clients to be able to download the files from the database. I am using c# and asp.net MVC for the site. what would be the easiest way to do this? I'm thinking about loading the blob into a bytearray and somehow passing the bytearray on but I don't know if this is possible.

mardi 10 mai 2016

An entity object cannot be referenced by multiple instances of IEntityChangeTracker"

this is my Class to cash the currently logged user when i am getting this error but i can figure it out while searching the error i am not getting any idea.my model class have the property public virtual User User{get;set;}

public static class Auth
{
    private const string UserKey = "BlogwithEf.Auth.UserKey";
    public static User User {
        get
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                return null;
            var user = HttpContext.Current.Items[UserKey] as User;
            if (user == null)
            {
                var db= new Database();
                user = db.Users.FirstOrDefault(u => u.Username == HttpContext.Current.User.Identity.Name);
                if (user == null)
                    return null;
                HttpContext.Current.Items[UserKey] = user;
            }
            return user;

        }
    }
}

this is my controller code

[HttpPost,ValidateAntiForgeryToken]
    public ActionResult New(PostsNew form)
    {
        if (!ModelState.IsValid)
            return View(form);

        var post = new Post
        {
            User = Auth.User,
CreatedAt=DateTime.UtcNow,
Title = form.Title,
Slug = form.Slug,
Content = form.Content
        };

        //Error is here

        Database.Posts.Add(post);

        Database.SaveChanges();

        return RedirectToAction("Index");

    }

lundi 9 mai 2016

Unit testing MVC app with Hangfire

Hi I am trying to setup unit testing for MVC 3 controllers that make use of Hangfire using OWin. Under normal operations, Hangfire gets configured in the Configuration function of the main controller like this

public void Configuration(IAppBuilder app)
{
    var sCon = ConnectionString.GetConnectionString();
    try
    {
        IUnitOfWork oUoW = UnitOfWorkFactory.GetInstance(sCon);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
        return;
    }
    app.UseHangfire(config =>
    {
        config.UseSqlServerStorage(ConnectionString.GetConnectionString());
        config.UseServer();
    });
}

I'm setting up HttpContextBase using Moq like this

private static HttpContextBase FakeAuthenticatedHttpContext()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    var response = new Mock<HttpResponseBase>();
    var session = new Mock<HttpSessionStateBase>();
    var server = new Mock<HttpServerUtilityBase>();
    var user = new Mock<IPrincipal>();
    var identity = new Mock<IIdentity>();
    var application = new Mock<HttpApplicationStateBase>();

    context.Setup(ctx => ctx.Request).Returns(request.Object);
    context.Setup(ctx => ctx.Response).Returns(response.Object);
    context.Setup(ctx => ctx.Session).Returns(session.Object);
    context.Setup(ctx => ctx.Server).Returns(server.Object);
    context.Setup(ctx => ctx.User).Returns(user.Object);
    context.Setup(ctx => ctx.Application).Returns(application.Object);
    user.Setup(ctx => ctx.Identity).Returns(identity.Object);
    identity.Setup(id => id.IsAuthenticated).Returns(true);
    identity.Setup(id => id.Name).Returns("admin");

    return context.Object;
}

moBaseController.SetFakeAuthenticatedControllerContext();

How do I fake the call to Configuration to setup the Job Storage. I have been looking at the Hangfire documentation and they are a little cryptic in this area and mention that job storage should be set up something like this

GlobalConfiguration.Configuration.UseSqlServerStorage("<connection string or its name>");
using (new BackgroundJobServer())
{
   BackgroundJob.Enqueue(() => ProcessReport(oReportRequest, JobCancellationToken.Null)));

}

however GlobalConfiguration is not known anywhere in the controller or unit test.

Check session object and return accordingly

I have following code in my controller actions. I have more than 15 controllers and more than 40 actions through out the application. Instead of checking session for each and every action, how nicely and bett

//Check if USER SESSION object is available
            if (Session["user"] != null)
            {
                //code
                return View();
            }
            else
            {
                return RedirectToAction("logout", "Home", new { area = "Common", value = "SessionTimeOut" });
            }

I just don't want to repeat the if statement for all 40 actions. Any better way of doing this?

Thanks,

Can't seem to get form values (in view) to the controller

I have 2 bits of code here.

This is my controller at the moment:

using System;
using System.Net.Mail;
using System.Web.Mvc;
using WebMatrix.Data;

namespace Best_prototype_01.Controllers
{
    public class RecrutaController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

            protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage Msg = new MailMessage();
                // Sender e-mail address.
                Msg.From = new MailAddress(txtEmail.Text);
                // Recipient e-mail address.
                Msg.To.Add("administrator@aspdotnet-suresh.com");
                Msg.Subject = txtSubject.Text;
                Msg.Body = txtMessage.Text;
                // your remote SMTP server IP.
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.Credentials = new System.Net.NetworkCredential("yourgmailemail@gmail.com", "yourpassword");
                smtp.EnableSsl = true;
                smtp.Send(Msg);
                //Msg = null;
                lbltxt.Text = "Thanks for Contact us";
                // Clear the textbox valuess
                txtName.Text = "";
                txtSubject.Text = "";
                txtMessage.Text = "";
                txtEmail.Text = "";
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} Exception caught.", ex);
            }
        }

    }

}

And this is the view that's supposedly associated with it (the part that matters anyways):

<form id="form1"  >
    <div>
        <table cellspacing="2" cellpadding="2" border="0">
            <tr><td></td><td><b>Contact Us Form</b></td></tr>
            <tr><td><b>Name</b></td><td><asp:TextBox ID="txtName"   /></td></tr>
            <tr><td><b>Email</b></td><td><asp:TextBox ID="txtEmail"   /></td></tr>
            <tr><td><b>Subject</b></td><td><asp:TextBox ID="txtSubject"   /></td></tr>
            <tr><td valign="top"><b>Message</b></td><td> <asp:TextBox ID="txtMessage" Rows="5" Columns="40" TextMode="MultiLine"   /></td></tr>
            <tr><td></td><td><asp:button ID="btnSubmit" Text="Submit"   onclick="btnSubmit_Click" CssClass="Button" /></td></tr>
            <tr><td colspan="2" style=" color:red"><asp:Label ID="lbltxt"   /></td></tr>
        </table>
    </div>
</form>

Can someone point me in the right direction? I have no clue what I'm doing wrong.

Popup no working when page change

I have a popup that ajax call him from a table , works well until you perform a new query that changes the data in the table . If I 'll call does not work, but does not Error(out for success)

My JavaScript

<script type="text/javascript">
    var theDialog = $('#my-dialog').dialog({
        autoOpen: false,
        modal: true,
        closeOnEscape: false,
        height: screen.availHeight - 100, 
        width: 1100,
        show: 'fade',
        hide: 'fade',
        resizable: 'false'
    });
    var myDialogProgress = $('#my-dialog-progress');
    var myDialogContent = $('#my-dialog-content');
   
    function showEventRegistrantSummary(id, ui) {
        $.ajaxSetup({ cache: false });
        myDialogProgress.show();
        theDialog.dialog('open');
        myDialogContent.html('');

        $.ajax({
            url: 'Home/Popup?id=' + id + '&ui=' + ui,
            type: 'GET',
            cache: false,
            dataType: 'html',
            success: function (data) {
                myDialogProgress.hide();
                myDialogContent.html(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Estado: " + textStatus); alert("Error: " + errorThrown);
            }
        });        
    }
</script>

A generic error occurred in GDI+, Getting this exception in my code when i try to save optimized image on server

Here is my code below which i am using to redraw and save the image.

Bitmap bitmap = new Bitmap(HttpContext.Current.Server.MapPath(filePath + Path.GetFileName(fileName)));

                    int newWidth = 100;
                    int newHeight = 100;

                    int iwidth = bitmap.Width;
                    int iheight = bitmap.Height;

                    if (iwidth <= 100)
                        newWidth = iwidth;

                    if (iheight <= 100)
                        newHeight = iheight;

                    bitmap.Dispose();

                    // ONCE WE GOT ALL THE INFORMATION, WE'll NOW PROCESS IT.

                    // CREATE AN IMAGE OBJECT USING ORIGINAL WIDTH AND HEIGHT.
                    // ALSO DEFINE A PIXEL FORMAT (FOR RICH RGB COLOR).

                    System.Drawing.Image objOptImage = new System.Drawing.Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);

                    // GET THE ORIGINAL IMAGE.
                    using (System.Drawing.Image objImg =
                        System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filePath + fileName)))
                    {

                        // RE-DRAW THE IMAGE USING THE NEWLY OBTAINED PIXEL FORMAT.
                        using (System.Drawing.Graphics oGraphic = System.Drawing.Graphics.FromImage(objOptImage))
                        {
                            var _1 = oGraphic;
                            System.Drawing.Rectangle oRectangle = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);

                            _1.DrawImage(objImg, oRectangle);
                        }

On the below lines of code i am getting error while i try to execute this code after uploading image. If image size is around 10 kb it will not throw any error but if it exceeds then 10 kb then it will.

 SAVE THE OPTIMIZED IMAGE.
                    objOptImage.Save(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + fileName),
                        System.Drawing.Imaging.ImageFormat.Png);**

                    objImg.Dispose();
                }

                objOptImage.Dispose();

                // FINALLY SHOW THE OPTIMIZED IMAGE DETAILS WITH SIZE.
                Bitmap bitmap_Opt = new Bitmap(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + Path.GetFileName(fileName)));
                byte[] bytes = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(filePath + "TempSubImages/" + Path.GetFileName(fileName)));

                UI.BasePage.TemporaryFile = bytes;
                String[] ArrContentType = new String[] { postedFile.ContentType, fileName };
                UI.BasePage.TemporaryStrings = ArrContentType;

                int iwidth_Opt = bitmap_Opt.Width;
                int iheight_Opt = bitmap_Opt.Height;
                bitmap_Opt.Dispose();

dimanche 8 mai 2016

object name is bind as prefix in input control

currently I am working in asp.net mvc view

I create form using below code.

@{
    T4.Models.Order o = new T4.Models.Order();
}

@using (Html.BeginForm("Create", "Default5", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Order</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
           @Html.LabelFor(model => o.CustomerID, new {@class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model=>o.CustomerID)
                @Html.ValidationMessageFor(model => o.CustomerID)
            </div>
        </div>
   </div>
}

this code render perfectly but problem is it render with prefix of object's name.

show below html code

<input class="text-box single-line" data-val="true" data-val-required="The CustomerID field is required." id="o_CustomerID" name="o.CustomerID" type="text" value="">

you can see this html input control has id="o_CustomerID".I want that it only render with id="CustomerID".

I does not know why it takes object name as prefix.

please help me.

Thank You.

vendredi 6 mai 2016

MVC EF Adding object to database

So this is a continuation of the question here

I am trying this below:

public DbSet<User> Users { get; set; }
public DbSet<Sport> Sports { get; set; }
public DbSet<Team> Teams { get; set; }

  • I can have many Sports
  • I can have many Teams in a Sport
  • I can have many Teams in a User
  • I can have many Users in a Team

Sport

public int ID { get; set; }
public List<Team> Teams { get; set; }

Team

public Team(int ID, int SportID, int Wins, int Losses, String Name, String Description, double Reputation, List<User> Members, byte[] TeamLogo)
 {
     this.ID = ID;
     this.SportID = SportID;
     this.Wins = Wins;
     this.Losses = Losses;
     this.Name = Name;
     this.Description = Description;
     this.Reputation = Reputation;
     this.Members = Members;
     this.TeamLogo = TeamLogo;
 }
public int ID { get; set; }
public List<User> Members { get; set; }
public int SportID { get; set; }

User

public int UserID { get; set; }
public List<Team> Teams { get; set; }

DB

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Adds middle table between Users and Teams
        modelBuilder.Entity<User>()
            .HasMany<Team>(t => t.Teams)
            .WithMany(m => m.Members)
            .Map(w => w.ToTable("UserTeam")
                       .MapLeftKey("UserID")
                       .MapRightKey("TeamID"));
    }

public void addTeam(Team team, String sport)
    {
        // Add the team to the correct sport
        Teams.Add(team);
        this.SaveChanges();
    }

Controller

model.NewTeam = new Team(0, db.getSportID(model.SelectedSport), 0, 0, model.TeamName, model.TeamDescription,
                   100, new List<User>() { model.currentUser }, model.ActualImage);
db.addTeam(model.NewTeam, model.SelectedSport);

Issue:

It adds a record to the Teams table just fine. It adds the record to the UserTeam table just fine. The problem is that it is also adding a new record to the User table as well so I have repeating users in my User table. Also, when I query the Teams Table, I get a null List Members so EF isn't properly getting the Members of each team from the Many-Many table.

Send Birthday E-Mail

Hi!

Im trying to create a function where i send Email to a user when it their birthday. I have all their personal data in my database, so I just wonder like where do i start? Or what do i do? Im creating this in an MVC app. This is what i've done so far.

public bool BirthdayEmail (int userId, int birthdate)
{
 var userbirthday = db.Contacts.Where(x => x.CustomerId == birthdate).FirstOrDefault();
}
return userbirthday;

jeudi 5 mai 2016

creating custom logic for focusing html elements while validating form

I have been stuck in somewhere around validating the form. I have a nice 10-11 fields in my .cshtml page in MVC. Those fields are using data anotations from model and here I am using client side validations using jquery and unobtrusive javascript. So, validations are firing up very good on submit but we need to implement a logic where a user will click on the submit button but the page will automatically drags the user to the location of mandatory field.

Assume that all 11 fields in my form are mandatory. user has filled the first two and left the third blank .So on submitting the form, the cursor should focus to that control with the validation message.Due to the length of the page, it should be scrolling up and down accordingly. And if suppose only first two fields are filled and others are empty, the validation message should show the 3rd field with the focus on control and then if user filled the 3rd field and hit save, it should focus to the fourth field.

On one instance it looks easy and I am trying it with following code snippet on click of submit button.

AS this is the class which mvc uses when validation fires, I select element from the first class like below:

 var element = $('#' + $('.input-validation-error:first').attr('id'));

once I get the element then I am using the below code:

 if (element.selector !== '#undefined') {

// The class "RequiredFeildDropdown" is applied to the control so that I can
 check if that is kendo dropdown and I should focus to that kendo control of the element.

        if (element.hasClass("RequiredFeildDropdown")) {
            element.data("kendoDatePicker").element.focus();
        }

// This class "RequiredFeildDate" has been applied to check whether the kendo control is datepicker
so that I can focus it.

        else if (element.hasClass("RequiredFeildDate")) {
            element.data("kendoDropDownList").focus();
        }

// So here comes the real problem.The primaryaddressData contains the collection of objects. Actually my page also consists of some table elements that i have created using for loop.

So, while validating , if primaryaddressData.length have count < 1, this div should show.Actually there should be atleast one primary address. The div which have table elemets is "primaryaddressErrorMessage"

 else {
        if (primaryaddressData.length >= 1) {
            $("#primaryaddressErrorMessage").hide();
        } else {
            $("#primaryaddressErrorMessage").show();
            $('html,body').animate({
                scrollTop: $("#primaryaddressErrorMessage").offset().top
            }, 'slow');
            isValid = false;
        }

        element.focus();

I am going very hard through this. There might be someone who has also faced this problem in past. So, it could be a duplicate question but I asked it for this particular scenario. Please let me know if some more explanation is required.

Installing Nuget package throws "An item with the same key has already been added" error

I have an MVC3 application which has a mixture of directly referenced binaries with paths such as:

C:\Users\Nick\Desktop\app\AppNamespace\bin\ActionMailer.Net.dll

and binaries installed via NuGet like this:

C:\Users\Nick\Desktop\app\packages\EntityFramework.6.1.1\lib\net45\EntityFramework.SqlServer.dll

I am trying to get the app to build only using NuGet so we don't have to move dlls into remote repositories

Taking ActionMailer as an example, here is what I am doing

  • remove the reference to ActionMailer.Net
  • install the package via package manager console which throws the following error:

    Attempting to gather dependency information for package 'ActionMailer.0.7.4' with respect to project 'SmartS.MVC3.ED', targeting '.NETFramework,Version=v4.5' Install-Package : An item with the same key has already been added.

  • This Stack Overflow post suggested finding what the stacktrace shows:

"$error[0].exception.stacktrace" An item with the same key has already been added. Unable to find type [T4Scaffolding.ScaffolderAttribute].[0].exception.stacktrace

  • I have tried looking up the T4Scaffolding.ScaffolderAttribute error but I haven't been able to find a solution

mercredi 4 mai 2016

How can i overload Index in MVC

I've Index page which is included Blogs from database. Firstly, if i dont give the categoryID then all blogs must come to index page. If i give the category then i want to display blogs by categoryID so i need use Index overload.

public ActionResult Index(){List<Blog> blogs = db.Blogs.ToList();}
public ActionResult Index(int ID){List<Blog> blogs = db.Blogs.Where(x=>x.CategoryID==ID).ToList();}

But when i want to display all blogs the error come like this:

The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Index() on type SosyalSozluk.Areas.Blog.Controllers.HomeController System.Web.Mvc.ActionResult Index(Int32) on type SosyalSozluk.Areas.Blog.Controllers.HomeController

How to default my entire application should run in IE 10 on server?

I deployed asp.net mvc application to the server. Now I would like to make my application should run default to IE10?

Thanks for the help in advance.

DB connection on the rel server?

    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-annaBevzenkoPortfolioMVC-20160425034146.mdf;Initial Catalog=aspnet-annaBevzenkoPortfolioMVC-20160425034146;Integrated Security=True" providerName="System.Data.SqlClient" />

- that is the connection which I use on my local machine. But when I deploy my app to the real server, there are problems with DB. For truth, I know nothing about DB-setup. As I understand, I should create a new MySql database using my hosting provider API and then change the coonection string in web.config? I've tried that way, but it doesn't work. I just dont understand what am I doing wrong?

P.S. The connection string which was generated by my hosting provider when I created a new MySql DB: <add name="DefaultConnection" connectionString="Server=MYSQL5017.Smarterasp.net;Database=db_9fcf5d_default;Uid=9fcf5d_default;Pwd=<my_password>;" providerName="System.Data.SqlClient" />.

How to call aspx page in mvc 5?

I am using MVC layout(RazorView Engine), this layout having menu. From this menu, i need to navigate aspx(Web form) and cshtml(view).

Anyone can help me out for the scenario.Please share sample code or tutorials.

mardi 3 mai 2016

Make webgrid table size fixed in MVC

I am using four webgrids in MVC vbhtml page. But unable to avoid resizing of those tables. Can anyone help me in this?

lundi 2 mai 2016

Httpget Method using asp.net mvc in controller

Fetch data from database some error occur here (AdminPurpose con = i.a ) Message show Cannot implicitly converted type.Please see below for my code snippets:

 public JsonResult GetInfor()
    {

        List<AdminPurpose> all = new List<AdminPurpose>();;
        using (db_Hajj_UmrahEntities dc= new db_Hajj_UmrahEntities()) {

            var datas = (from  a in dc.Duas join b in dc.Purposes on a.PurposeId equals b.Id

               select new {
                   a,
                   b.PurPose1
        });


            if(datas != null) {


                foreach (var i in datas)
                {
                    AdminPurpose con =  i.a ;
                    con.PurPose1 = i.PurPose1;
                    all.Add(con);
                }
            }
        }

        return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

Model class one to many relation here it's using

[MetadataType(typeof(DuaMetaData))]
public partial class AdminPurpose
{
    public string PurPose1 { get; set; }
}

public class DuaMetaData
{

    public string Dua_Name { get; set; }
    public string Arabic_Word { get; set; }
    public string Translation_English { get; set; }
    public string Source { get; set; }

    [Display(Name = "Purpose")]
    public int PurposeId { get; set; }


}

MVC AJAX Updating

I am trying to update my page with ajax and have a form inside my page but whenever I return a partial view, it returns on a new page.

The code is as follows:

..Other code in my view
<div id="createTeam">
    @using (Ajax.BeginForm("CreateTeam", "Lobby", new AjaxOptions
    {
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "createTeam"
    }, new { id = "formCreateTeam" }))
    {
        <button id="btnCloseCreateTeam" class="btnClose">X</button>
        <div id="leftSide">
            <p>Team Logo</p>
            <img id="imgTeamLogo" src="~/Content/Images/default_logo.png" />
            <div id="fileUpload">
                <span class="upload">Upload</span>
                <input type="file" id="uploadTeamLogo" name="TeamLogo" accept="image/*">
            </div>
        </div>
        <div id="rightSide">
            <p id="lblError" class="txtRedMedium">@Model.Error</p>
            @Html.ValidationMessage("TeamName", new { @class = "textRedSmall" })
            <label class="textBlackMedium">Team Name:</label><br />
            <input type="text" id="editTeamName" name="TeamName" class="textbox"><br />
            <label class="textBlackMedium">Team Description:</label><br />
            <textarea id="editTeamDescription" name="TeamDescription" class="textarea"></textarea><br />
            <input type="submit" value="Create Team" class="buttonCreateTeam">
            <input type="text" value="@Model.Sport.Name" name="sport" />
        </div>
    }
</div>
...Other code in my view

Controller function:

public PartialViewResult CreateTeam(LobbyMatchesViewModel model, String sport)
    {
        model.Sport = new Sport();
        model.Sport.Name = sport;
        model.TeamCreated = false;

        /****************** Create Team *******************/

        // Check if team name is available
        Team tempTeam = db.getTeamByName(model.TeamName, sport);
        if (tempTeam != null)
        {
            // Team name for this sport is already taken
            model.Error = "Team name is already taken!";
            return PartialView("CreateTeam", model);
        }
        // Add image to user
        if (model.TeamLogo != null)
        {
            byte[] data = new byte[model.TeamLogo.ContentLength];
            model.TeamLogo.InputStream.Read(data, 0, model.TeamLogo.ContentLength);
            model.ActualImage = data;
        }
        model.TeamCreated = true;
        model.NewTeam = new Team(0, db.getSportID(sport), 0, 0, model.TeamName, model.TeamDescription, 100, null, model.ActualImage);
        db.addTeam(model.NewTeam, sport);
        return PartialView("CreateTeamSuccess");
    }

I don't understand why it is loading a new page rather than just the div "createTeam". It is sending me to a page Lobby/CreateTeam instead of Lobby/Matches which is what I am on when I submit the form. Shouldn't Lobby/CreateTeam just render a partial view back to Lobby/Matches?

Is ControllerBase.Execute(RequestContext) obsolete in MVC5?

I am upgrading a web site from MVC3 to MVC5. I simply used NuGet to install Microsoft.AspNet.Mvc version 5.2.3 and everything seemed to be working fine. But upon closer examination I noticed that this code was no longer running:

public abstract class BaseController : System.Web.Mvc.Controller
{
    protected override void Execute(RequestContext requestContext)
    {
        LogRequest();
        UpdateUserSession();
        base.Execute(requestContext);
    }
}

I found this lifecycle documentation (linked from here) which seems to confirm that Execute is no longer called by MVC.

However, this documentation is unclear, saying

This method is an implementation of Execute. You typically do not have to override this method. Override Initialize or ExecuteCore instead.

I would expect it to say "This method is no longer called by the MVC framework as of version 5 (or maybe 4)." Perhaps even mark it [Obsolete], although there may have been good reasons not to do that.

Furthermore, my testing shows that ExecuteCore does not get called either! It looks like OnActionExecuting is the best place to move the code that used to live in Execute, is that correct?

get checked check-box value using form-collection

I have check-box input field on the view page as given below-

<input type=@item.InputType.ToString().Trim().ToLower() id="@item.AdminAnswers.ElementAt(i).Answer" value="@item.AdminAnswers.ElementAt(i).Answer" name="@item.Id"></input>@item.AdminAnswers.ElementAt(i).Answer

and in the controller am getting data using form collection as given below-

public ActionResult Index(FormCollection data)
    {
        foreach (var item in surveyDatas)
        {           
            if(item.InputType.ToString().Trim().ToLower() == "checkbox")
            {
                var dev =item.NumberOfChoice;
                for (int i = 1; i < dev; i++)
                {
                    //here I need to iterate checked checkbox value
                }
            }
            myclientanswer.DevAnswers = devAnswer;              
            clientAnswer.Add(myclientanswer);
        }
        return View("LoginResult");
    }

How can I iterate only checked check-box values over there??

Filtering the records in c# from view

I am having a view which is like

CREATE view [dbo].[vw_myList]

as

SELECT tblOrg.locationName Name, 

       tblOrg.locationID Id,

       from tables with some joins.

as you can see I am not having any accepting paramameter for this view but now I have one condition on some another web page that will be using this view but it needs to filter the selected records from this view using locationId

like where locationId = @argument

I have tried to use it like below:

       var locationList = this._Service.GetlocationLists();

List<mymodel> objlist = new List<mymodel> objlist

// This gets all records

  var list= locationList .Select(m => new mymodel
            {
                 name = Name, id= Id
            });

but i wanted to use it like but it is not working

  var list= locationList.where(m=>m.id==@argument).Select(m => new mymodel
            {
                 name = Name, id= Id
            });

How to solve Uncaught TypeError: $(...).datepicker is not a function

<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
    $(function () { $("#datepicker").datepicker();});
</script>

This is my Layout.cshtml

@Html.TextBoxFor(m => m.Date, new { @id = "datepicker", @style = "width:150px;" })

Index

But the datepicker cannot be showed and it shows Log:13 Uncaught TypeError: $(...).datepicker is not a function(anonymous function) @ Log:13fire @ jquery-1.9.1.js:1037self.fireWith @ jquery-1.9.1.js:1148jQuery.extend.ready @ jquery-1.9.1.js:433completed @ jquery-1.9.1.js:103 in the console

Why Aspx view engine is faster than razor view engine in MVC?

I see lot of Differences Between Razor View Engine and ASPX View Engine But I am not able to understand that why Web Form Engine is faster than Razor Engine ? What is the reason behind it ?

Can MVC deserialize the json string which is having perl_script naming convention

We are working with the third party vendor who is passing following object as part of Form post

{
    "application": 123,
    "order_reference": "01234",
    "new_status": "initialize"
}

As this is not the standard naming convention in C#, i created following model.

public class Response
{
    [JsonProperty("application")]
    public string Application {get; set;}

    [JsonProperty("order_reference")]
    public string OrderReference {get; set;}

    [JsonProperty("new_status")]
    public string NewStatus {get; set;}
}

And i have below code in controller.

[HttpPost]
public Notify(Response response)
{
   // code.
}

The request is coming to the above method, but the object is not deserializing, I could see that, only application property is getting mapped.

Could any one please let me know, whether i can make it work with the model i have created or do i have to create the same model as the response is coming?

dimanche 1 mai 2016

MVC ReturnUrl link error

I'm working on ReturnUrl in mvc but i have some url link error.

a href="/User/Login?returnurl=/Forum/Detail/@item.ID" with this link going to Login view and carrying returnurl parameters.

In the login page i catch returnurl querystring with this code

string url = Request.QueryString["returnurl"];

        if (ModelState.IsValid)
        {
            if (db.Users.Any(x => x.Mail == model.EMail && x.Password == model.Password && x.IsDelete == false))
            {
                FormsAuthentication.SetAuthCookie(model.EMail, true);

                if (!string.IsNullOrEmpty(url))
                {
                    return RedirectToAction(url);
                }
                return RedirectToAction("Index", "Home");

After when i click sign in i cannot go back to my first url. Link turn this http://localhost:61476/User/Forum/Detail/3

I want to turn back this url: http://localhost:61476/Forum/Detail/3

Working with tempdata in mvc

As I have read that once you set a tempdata, it will last till next request and if you need to use it more then we need to use keep. But in this situation there is somewhere my tempdata is being lost.

The scenario is below:

I have a view and corresponding to that I have a action method in my controller and here I just set a tempdata as below:

Controller class:

public actionresult myview()
{
   tempdata["Empid"]= sourceid;
} 

The view consists of several renderAction as below and all these actionmethods in controller return some partialviews

@html.renderAction("details","mycontroller")
@html.renderAction("details","mycontroller")
@html.renderAction("details","mycontroller")
@html.renderAction("details","mycontroller")

Now in partialviews, I have several ajaxified calls suppose in one of the partialview , I have a post method using ajax like below:

$.post("action", "controller",{}});

Please ignore syntactical mistakes as I only have problem in understating the logic of tempdata.

So, coming to above, now the post methods have actionmethods that uses the tempdata that i have set when my view page loads i.e tempdata["Empid"] because this tempdata is needed to get details of employee.

So, it gets the data, reurn json formatted data and I show it in view perfectly. Uptill here everything is fine. Now, I have one of the partialviews that uses the ajax post to hit controller which is not the same controller but a different cs file. Here this tempdata goes off.

Why is it happening so..

How to Update DataBase with an ActionLink in a List Page

I have an ActionLink (for update) in a list (strongly type List for display list db) page. Now I'm using the ActionLink update, change the other Family of database to a string.

    public bool Update()
    {
        User old_user = db.Users.Where(p => p.Family == "Jacki").Single();
        old_user.Family = "Anderson";
        return Convert.ToBoolean(db.SaveChanges()); 
    }

    public ActionResult changeFamily(User Us)
    {
        blUs.Update(Us);
        return RedirectToAction("List");
    }