mercredi 6 mai 2015

Remote validation is not working

When I entered value for email in textbox it didn't fire VerifyUserEmail method. Below is my code. Where is my mistake?

View

<div class="form-group">
    @Html.LabelFor(model => model.User_Email, new { @class = "control-label col-lg-2" })
        <div class="col-lg-4">
            @Html.EditorFor(model => model.User_Email)
            @Html.ValidationMessageFor(model => model.User_Email)
        </div>
</div>

Model

[DisplayName("Email")]       
[Remote("VerifyUserEmail", "User", ErrorMessage = "Email already exists!")]
public string User_Email { get; set; }

Controller

    public JsonResult VerifyUserEmail(string User_Email)
    {
        try
        {
            using (RKDYMEntities objConnection = new RKDYMEntities())
            {
                ObjectParameter objIErrorCode = new ObjectParameter("ErrorCode", typeof(Int32));
                ObjectParameter objBFlag = new ObjectParameter("bFlg", typeof(bool));
                objConnection.Check_User_Exists(User_Email, objBFlag, objIErrorCode);

                if (Convert.ToBoolean(objBFlag.Value) != true)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }


            }
        }
        catch (Exception Ex)
        {
            return Json(false, JsonRequestBehavior.AllowGet);
        }
    }

I have also added <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> in web.config.

Below is generated html code:

 <div class="form-group">
    <label class="control-label col-lg-2" for="User_Email">Email</label>
        <div class="col-lg-4">
            <input class="text-box single-line" data-val="true" data-val-length="The field Email must be a string with a maximum length of 200." data-val-length-max="200" data-val-remote="Email already exists!" data-val-remote-additionalfields="*.User_Email" data-val-remote-url="/User/VerifyUserEmail" id="User_Email" name="User_Email" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="User_Email" data-valmsg-replace="true"></span>
       </div>
 </div>

Send double value to MVC controller as a string

I've got an action in my controller

    [HttpGet]
    [Route("classificators/{type}/{criteria}/{predicate?}")]
    public ActionResult Classificators(string type, string criteria, string predicate)
    {
        try
        {
            //Lot's of cool code here!          

            return Json(new { Data = "Cool data!" }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new
            {
                state = "error",
                message = ExceptionReport(ex)
            }, JsonRequestBehavior.AllowGet);
        }
    }

And sending request to it like so..

/classificators/MAIN/CODE/50.1

Where: type - MAIN criteria - CODE predicate - 50.1

But action treats parametr 50.1 like double value so I've got an error. How to specify action to treat this value like a string

Image displaying error from database

After the recent changes in my application still i get this issue while displaying the image using the relative path in the database. Error: 404 NOT FOUND http://localhost:1256/Empdet/%22/Photos/jobs.jpg%22

Screenshot

Controller.js:

 $scope.UploadFile = function () {
    console.log('UploadFile');
    console.log($scope.Empdet.PhotoFile);
    var file = $scope.Empdet.PhotoFile;
    console.log('file is ' + JSON.stringify(file));
    var uploadUrl = "../Photos";
    console.log('before file upload');
    EmployeeFactory.UploadFile(file, uploadUrl).success(function (response)  {
        $scope.Empdet.PhotoText = response;
        console.log('$scope.Empdet.PhotoText');
        console.log(response);
    }).error(function () {
        console.log('error');
    });
    console.log('after file upload');
};

service.js:

service.UploadFile = function (file, uploadUrl) {
    var fd = new FormData();
    fd.append('file', file);
    return $http.post('/Empdet/UploadFile', fd, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    });
}

EmpdetController.cs:

[HttpPost]
    public ActionResult UploadFile()
    {
        var file = Request.Files[0];
        var path = Path.Combine(Server.MapPath("~/Photos/"), file.FileName);
        file.SaveAs(path);

        // prepare a relative path to be stored in the database and used to display later on.
        var filename = Url.Content("~/Photos/" + file.FileName);
        // save to db
        return Json(filename.ToString(), JsonRequestBehavior.AllowGet);

    }

How to disable radio button overwrite?

I have second thing on my page: In array (Completed is bool):

@Html.EditorFor(m => Model.Options[i].Completed)

As html this looks like

<td>
    Yes 
    <div id="Options_0__Completed-styler" class="jq-radio" unselectable="on" style="-webkit-user-select: none; display: inline-block; position: relative;">
        <input id="Options_0__Completed" name="Options[0].Completed" type="radio" value="True" style="position: absolute; z-index: -1; opacity: 0; margin: 0px; padding: 0px;">
        <div class="jq-radio__div"></div>
    </div>
    No
    <div id="Options_0__Completed-styler" class="jq-radio checked" unselectable="on" style="-webkit-user-select: none; display: inline-block; position: relative;">
        <input checked="checked" id="Options_0__Completed" name="Options[0].Completed" type="radio" value="False" style="position: absolute; z-index: -1; opacity: 0; margin: 0px; padding: 0px;">
        <div class="jq-radio__div"></div>
    </div>
</td>

My issue is that potentialy, because of jq-radio (comes from jquery.formstyler.js) I can't do any change for radio buttons.

For example:

    for (var i = 0; i < value; i++) {
        var test = $('input[name="Options[' + i + '].Completed"]').filter('[value=False]');
        test.attr('disabled', true);
    }

If I look on html, then I will see that input with value False is disabled, BUT visually, nothing changes for be.

How can I fix this kind of issue?

Inherited RoutePrefixAttribute in ASP.NET MVC

Currently, my ASP.NET MVC website uses RouteConfig.RegisterRoutes to map routes. I would like to convert this to the new Attribute routing system, but I am missing one small thing there.

The website is multi-language, so every URL needs to be prefixed with a two-letter ISO language code. In the current implementation, the website uses a custom RouteHandler to handle the culture part of all routes. After registering all routes, a loop adds the custom handler and culture constraints to every route.

See below the current implementation:

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

        routes.RouteExistingFiles = true; 

        // various calls to routes.MapRoute()

        foreach (Route r in routes)
        {
            if (!(r.RouteHandler is SingleCultureMvcRouteHandler))
            {
                r.RouteHandler = new MultiCultureMvcRouteHandler();
                r.Url = "{culture}/" + r.Url;

                // Add the default language
                if (r.Defaults == null)
                    r.Defaults = new RouteValueDictionary();
                r.Defaults.Add("culture", Culture.nl.ToString());

                // Add language constraints
                if (r.Constraints == null)
                    r.Constraints = new RouteValueDictionary();
                r.Constraints.Add("culture", new CultureConstraint(Culture.nl.ToString(), Culture.de.ToString(), Culture.en.ToString(), Culture.fr.ToString()));
            }
        }
    }
}

Culture enum:

public enum Culture
{
    nl = 1,
    en = 2,
    de = 3,
    fr = 4
}

Custom routehandler:

public class SingleCultureMvcRouteHandler : MvcRouteHandler { }

public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var culture = requestContext.RouteData.Values["culture"].ToString();
        var ci = new CultureInfo(culture);
        Thread.CurrentThread.CurrentUICulture = ci;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("nl-NL");

        return base.GetHttpHandler(requestContext);
    }
}

Culture constraints

public class CultureConstraint : IRouteConstraint
{
    private string[] _values;
    public CultureConstraint(params string[] values)
    {
        this._values = values;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        string value = values[parameterName].ToString();
        return _values.Contains(value);
    }
}

In order to convert this to the new AttributeRouting, I just thought I'd add a RoutePrefix attribute to my base controller, which would handle the culture part. BUT it seems inheritance of route attributes is not supported...

The release notes of ASP.NET MVC 5.2 state that inherited route attributes are supported in that version by implementing a custom RouteAttribute and DirectRouteProvider. This is however for the RouteAttribute, not for the RoutePrefixAttribute.

What I have tried:

I've tried to create my own InheritedRoutePrefixAttribute by inheriting from the RoutePrefixAttribute, but then in order to actually support the inherited route, I still need to create a InheritedDirectRouteProvider and override the GetControllerRouteFactories() method, which returns a collection of IDirectRouteFactory.
So in order to do that, my InheritedRoutePrefixAttribute needs to implement the IDirectRouteFactory interface, but what to do in the CreateRoute() method?

My code so far:

[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class InheritedRoutePrefixAttribute : RoutePrefixAttribute, IDirectRouteFactory
{
    public RouteEntry CreateRoute(DirectRouteFactoryContext context)
    {
        // ...
    }
}

Custom route provider

// Custom direct route provider which supports attribute route inheritance.
public class InheritedDirectRouteProvider : DefaultDirectRouteProvider
{
    protected override IReadOnlyList<IDirectRouteFactory> GetControllerRouteFactories(ControllerDescriptor controllerDescriptor)
    {
        return controllerDescriptor.GetCustomAttributes(typeof(InheritedRoutePrefixAttribute), inherit: true).Cast<IDirectRouteFactory>().ToArray();
    }
}

ASP.NET MVC customError page doesn't get displayed for some of the 400 errors

I'm having quite an interesting issue with the custom error pages management for a new ASP.NET MVC application.

This issue is like this:
- if I'm calling an URL (doesn't matter which) with a "bad" argument at the end of URL, like ..../c<, the application is displaying the correct server error page as instructed in the web.config;
- if I'm changing the URL to a more nasty one, like .../<c (to look more like an HTML tag, there is no more server error page displayed in the browser and instead of that, I'm getting a plain YSOD with a message like An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.

According to ELMAH, both requests ended with a 400 status code and the message being:
- for the first one: System.Web.HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (<). at System.Web.HttpRequest.ValidateInputIfRequiredByConfig() at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)
- for the second one: System.Web.HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (<). at System.Web.HttpRequest.ValidateInputIfRequiredByConfig() at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)

So, both errors are the same, the status code is the same, but for one of the errors, the custom error page is not getting displayed. I've also went to global.asax in debug mode and checked the Server.GetLastError() in protected void Application_Error(object sender, EventArgs e) and again, both errors were the same, nothing is different.

In web.config, this is how my <customErrors> tag looks like:

<customErrors mode="On" defaultRedirect="/ServerError.aspx" redirectMode="ResponseRewrite"> <error statusCode="500" redirect="/ServerError.aspx" /> <error statusCode="404" redirect="/PageNotFound.aspx" /> </customErrors>

Can please someone tell me why the behavior is different in these two cases?

Thank you very much for your time.

Which version should i start for MVC

I am new in MVC Framework, I have just developed application in web form application till now Please suggest me, may i start MV3 or MVC 5 ?

404 after changing routes in ASP NET MVC application

I had working routes on my app that looked like this:

            routes.MapRoute(
            name: "Category",
            url: "{name}-c{categoryId}",
            defaults: new { controller = "Products", action = "Index", name = "ErrorName" },
            namespaces: new[] { "B2B.Controllers" });

        routes.MapRoute(
            name: "InfoPage",
            url: "{name}-i{id}",
            defaults: new { controller = "InfoPages", action = "Details", name = "ErrorName" },
            namespaces: new[] { "B2B.Controllers" });

I've changed the dash (-) to the hash (#) because spaces are changed in url to dashes.

 url: "{name}#c{categoryId}",
 url: "{name}#i{id}",

Now I've this same routes with only this one char changed and I get 404 on urls like this:

siteadess:1234/1.0.1-Podstawowa%23c4

I've also tried to change hash to under score and it didn't worked either.

Manipulate the url using routing

In my website i have the following route defined:

routes.MapRoute(
   name: "Specific Product",
   url: "product/{id}",
   defaults: new { controller = "", action = "Index", id = UrlParameter.Optional }
);

in that way i want customers to be able to add the id of the product and get to the product page.

SEO advisors have said that it would be better if we could add a description of the product on the url, like product name or something. So the url should look like something like:

/product/my-cool-product-name/123

or

/product/my-cool-product-name-123

Of course the description is stored in the db and i cannot do that with a url rewrite (or can i?)

Should i add a redirection on my controller (this would seem to do the job, but it just doesn't feel right)

Umbraco 7 Custom Controllers not working

I have two umbraco sites, one on version 7.1.8 the other on 7.2.4. The site with 7.1.8 has several controllers all of which inherit from PluginController. Other than inheriting from PluginController there have been NO modifications to the models i.e. inheriting from Umbraco.Web.Models.RenderModel or in the view. It simply works just like normal asp.net MVC. The controllers have no reason to talk to Umbraco.

My second site however doesn't seem to want to work in the same way. Error messages insisting I used Umbraco.Web.Models.RenderModel etc.

Is there any way to tell Umbraco leave my controllers alone like in the first site?

Image uploader on register view

I have a process where a user can register and add a picture of himself via an image file stored locally. The problem I am facing with a lot of image browsers openly available is either they require something as follows:

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

I am not that knowledgeable in MVC,Can someone suggest the approach I should take in handling this issue?

Image should be uploaded on clicking Register. Almost all of the image uploaders I found had a dedicated button for uploading.

Dynamically accessing resource file properties from Razor

We have a partial view which renders a <ul> containing <li> items that represent menu items. These are currently static in structure, and handle multilingual with resource files as follows:

<li><a href="@Url.Action("commissionlist", "commissions")">@Resources.Labels.Commissions</a></li>

However, I need to dynamically build the menu structure. So I have a list of menu item objects, which each have a MenuResourceTag field.

How do I get from having a string representing the name of the property I need to look up (e.g. "Commissions") to accessing the value of the appropriate property on Resources.Labels?

I know the answer will involve reflection, but all the examples I've found of similar things require an instance of the Resources.Labels class, and I can't work out how to get it in Razor.

ASP.Net MVC - Two Step Authentication

Good Morning

In MVC there is a method in the manage controller being used. to generate a token.

  var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);

Does anyone know where this generated token is saved. In the basic MVC example they use it to add a phone number and needs to be verified with the token being sms`d to the cellphone number supplied, this code is used to generate that token. But no where is that token being saved, there is no column in the db and is not being passed to the view in a hidden field. But the strange part is when you enter the code and submit it, it will do a comparison in the post method using the following

    public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
    {
       var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber);
       // Send an SMS through the SMS provider to verify the phone number
       return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
    }

I cannot figure out where the GenerateChangePhoneNumberTokenAsync method will find the generated token to compare with the token being passed in with the model. Do anyone of you have and idea of where this could be found.

Kind Regards

Change model values before process through actions

How can I change sent data to controllers some where like OnActionExcuting? Imagine I want develop a middle ware (something like asp.net attributes) replace all "a" to "A" and then bind values to model(in all action just can see "A"!)

reserved keywords like CON, PRN, NUL in URL in ASP.net MVC

I tried to hit URL with id as CON in ASP.net MVC.

Routing

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

Its giving following error

2015-04-29 08:25:22,325 [8] FATAL Myapplication.Global - Application ERROR === (null)
System.Web.HttpException (0x80004005)
   at System.Web.CachedPathData.GetPhysicalPath(VirtualPath virtualPath)
   at System.Web.CachedPathData.GetConfigPathData(String configPath)
   at System.Web.HttpContext.GetFilePathData()
   at System.Web.HttpContext.GetRuntimeConfig()
   at System.Web.HttpContext.get_ImpersonationToken()
   at System.Web.ClientImpersonationContext.Start(HttpContext context, Boolean throwOnError)
   at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)
   at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
   at System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(Exception error)

mardi 5 mai 2015

Hide vertical scrollbar for specific page in mvc 4

Using following css code I can disable vertical scroll bar for whole mvc 4 project view files.

body {
 overflow-y: hidden!important;
}

But how to disable vertical scrollbar for specific cshtml view page

Dynamically change java script and css files of different modules in an application

In my Asp.net MVC 5 application i currently have three modules and each module have it's own script files and style sheet files and there are some common scripts and style sheet files also, these are available to all the modules and even to entire application.

Currently i have one main div and i replace the entire html of that div with the opening module using jquery ajax and it's working fine, but in this way my modules state is not persistent means after opening second module if i open previously opened module it will be opened from it's initial state.

Now i want to persistent the state of each opened module. One approach in my mind is that i make three different empty div and replace the html of each respective module to it's own div and if any module's div is not empty then i just show that div and hide the remaining divs but in this way i think scripts and css files references of individual modules will not be removed when another module in opened.

Kindly please guide me how can i achieve that only currently opened module scripts and css files are referenced in the page and remaining files references are removed along with my html of each module is persistent.

Thanks in advance. :)

Custom Time Validation by Data annotation in MVC

I am trying to implement custom validation in my MVC application. My scenario is

If Closed checkbox is checked, Start and End times are not required.

If Closed checkbox is not checked, I want user to select start and End times from dropdown.

If user select start and end times, I want to validate end time should be greater than start time.

I wrote a custom validation class as below. How can I validate this ?

 public class DatesValidation : ValidationAttribute
{
    public bool Closed { get; set; }

    public string Start { get; set; }

    public string End { get; set; }

    public DatesValidation(bool closed, string startTime, string endTime)
    {
        this.Closed = closed;
        this.Start = startTime;
        this.End = endTime;
    }
}

Using the collection's DisplayName from within DisplayTemplate for a single element

To begin with, the code we have no problems with. It's a model:

    [DisplayName("A very hot hotshot")]
    public Person Hotshot { get; set; }

    [DisplayName("Just a developer")]
    public Person Developer { get; set; }

    [DisplayName("Some random guy")]
    public Person RandomGuy { get; set; }

And then we have a view which looks like this:

@Html.DisplayFor(m=>m.Hotshot)
@Html.DisplayFor(m=>m.Developer)
@Html.DisplayFor(m=>m.RandomGuy)

DisplayTemplate for Person has a line which uses model's DisplayName:

@Html.DisplayNameForModel()

It's all nice, but the problem appears when you add a list property to the model and try to display it with DisplayFor. Here's the model part:

[DisplayName("Funny guys")]
public IEnumerable<Person> FunnyGuys { get; set; }

And, as DisplayFor is capable of displaying IEnumerable<T> iterating the T template, I'm calling it just like for other properties:

@Html.DisplayFor(m=>m.FunnyGuys)

It works great, except for fetching that DisplayName from the containing collection. It's set to null, since the attribute is on IEnumerable property, and the template gets a single element from it.

I had to use the workaround:

@Html.DisplayFor(m=>m.FunnyGuys, new {CollectionDisplayName = "Funny guys"})

And then using that property if DisplayName is null in Person template.

Is there a cleaner way?

Exception when I use Html action

I'm getting this error from @Html.Action("getCategory", "Blogs") in the master layout for my blog.

The error is:

An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code Additional information: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.

Here is my controller:

public ActionResult getCategory()
    {
        var categories = _repo.getBlogs().Select(c => new
        {
            c.Category
        }).ToList();
        return PartialView("_category", categories);
    }

And here is my partial view:

@model  IEnumerable<MainSite.Data.Blog>

<div class="sw_categories">
<div class="sw_title">
    <h4>Categories</h4>
</div>
<ul class="arrows_list">
    @foreach (var c in Model)
    {
        <li><a href="#">@c</a></li>
    }
</ul>
</div>

I'm pretty new to ASP.NET MVC, so could anyone please explain the error to me and how I could fix this?

drop down list selection to generate tabel [on hold]

I have 3 drop down lists (list items are not bound with data base) in my page and a click button, I want that on click even all three selections should come in form of table and so on at every click

How to revert radio button checked change?

I have a .change() placed for each radio button in table:

    for (var i = 0; i < Count; i++) {
        $('input[name="Options[' + i + '].Completed"]').change(function () {
            var number = $(this).attr("name").match(/\d+/g)[0];
            ...
            some action
            ...
        });
    }

What I'm tryin to do is to revert radio botton change in case of some condition.

By default, my radiobutten is marked as false (Yes No, No by default). If I clicked to Yes, but don't mach the condition, I need to stay on No.

I have tried to do this in this way:

if (... condition ...) {
     $('input[name="Options[' + i + '].Completed"]').filter('[value=False]').prop('checked', true);
}

But this doesn't seems to work (nothing happened, but condition works fine).

What am I doing wrong and how can I accomplish my goal?

EDIT:

radiobutton html:

<input id="Options_0__Completed" name="Options[0].Completed" type="radio" value="True" style="position: absolute; z-index: -1; opacity: 0; margin: 0px; padding: 0px;">
<input checked="checked" id="Options_0__Completed" name="Options[0].Completed" type="radio" value="False" style="position: absolute; z-index: -1; opacity: 0; margin: 0px; padding: 0px;">

Unable to display image

When i try to execute my application all the data's in the database r getting displayed and instead of storing image i stored its path in DB and displaying the image but when i render it in chrome i says

Error: 404 not found

But when i check it physically the images are present in folder where i uploaded.

Screenshot:

screenshot of my output

EmpdetController.cs

[HttpPost]
    public ActionResult UploadFile()
    {
        var file = Request.Files[0];
        var path = Path.Combine(Server.MapPath("~/Photos"), file.FileName);
        file.SaveAs(path);

        // prepare a relative path to be stored in the database and used to display later on.
        var filename = path;
        // save to db
        return Json(filename.ToString(), JsonRequestBehavior.AllowGet);

    }

EmpdetList:

<h2>EmpdetList</h2>

<table class="table table-bordered table-hover table-striped" ng- table="tableParams" show-filter="true">
<tr ng-repeat="Empdet in EmpdetList">                       
    <td data-title="'Id'" filter="{ 'Id': 'text' }" sortable="'Id'">{{Empdet.Id}}</td>
    <td data-title="'FirstName'" sortable="'FirstName'" filter="{ 'FirstName': 'text' }">{{Empdet.FirstName}}</td>
    <td data-title="'LastName'" sortable="'LastName'" filter="{ 'LastName': 'text' }" >{{Empdet.LastName}}</td>
    <td data-title="'Email'" sortable="'Email'" filter="{ 'Email': 'text' }">{{Empdet.Email}}</td>
    <td data-title="'PhotoText'" sortable="'PhotoText'" filter="{ 'PhotoText': 'text' }"><img ng-src={{Empdet.PhotoText}} class="img-responsive"/></td>
    <td data-title="'Age'" sortable="'Age'" filter="{ 'Age': 'text' }">{{Empdet.Age}}</td>

    <td data-title="'Action'">
        <div data-toggle="modal" data-id="{{Empdet.Id}}" data-index="{{$index}}" data-name="{{Empdet.Id}}" ng-click="DeleteEmployee(Empdet.Id)"  title='Click to delete the Account' class="open-confirm-delete fa fa-trash-o deleterow" style="height: 24px!important;">
        </div>
    </td>
</tr>
</table>

String should not start with ! or = Regex Expression

I am looking for a regex which doesn't allow string to be started with either '!' or '='. Here is my code at the moment in which I have only added the code for '=' which doesn't work.

[RegularExpression("^(?!=)", ErrorMessageResourceName="Error_StringStartWith",      ErrorMessageResourceType= typeof(CommonStrings))]
public String FirstName { get; set; }

I want to redirect user to new page with his login details appended in the url [on hold]

My question is- Suppose a user uses facebook to login then i want to redirect user to new page with his login details appended in the url.How to achieve this in asp.net mvc.Will query string be able to fetch details from social login page as we does with normal forms.

Kendo grid populates and posts all of the navigation properties

I have a Kendo Grid for Serial class. This class has relation with row class, but I don't use any of the navigation properties in my Grid and I don't need them in this particular page.

The problem is Kendo populates all of the foreign key relations. So the row class and all of the navigation properties of itself will be populated. When I try to save my edit, Kendo posts all of these data and this causes ModelState.IsValid always be false. Do you have any suggestion?

This is the Serial class, and I have a field for each property.

public class Serial
{
    [Key]
    [Column(TypeName = "BIGINT", Order = 0)]
    public Int64 LiIdR { get; set; }
    [ForeignKey("LiIdR")]
    public virtual Rows Row { get; set; }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Int16 SRadifS { get; set; }
    public string AFromSerial { get; set; }
    public string AToSerial { get; set; }
    public int? IQnty { get; set; }
    public string AExpireDate { get; set; }
    public string AComment { get; set; }
}

Kendo UI Grid - Add new record

I am using kendo UI grid with inline Add/Edit. In that I have button which adds new row to the grid to add new record.

My problem is if I keep clicking on "Add New Record" button it will keep adding new row to the grid.

Below is my code for grid:

@{Html.Kendo().Grid<myclass>()                                    
                                .ToolBar(t => t.Create().Text("Add New Record"))
        .Name("MyGrid")
        .Filterable()
                                  .Events(e => e.Edit("onEdit"))
        .DataSource(dataSource => dataSource
                      .Ajax()
            .Events(e => e.Error("Error_handler").RequestEnd("onGridRequestEnd"))
                      .ServerOperation(false)
                      .Model(model => model.Id(p => p.id))
                      .Read(read => read.Action("_AjaxBinding", "MyController").Type(HttpVerbs.Post))
                      .Create(create => create.Action("_SaveAjaxEditing", "MyController").Type(HttpVerbs.Post))                          
                      )
    .Columns(columns =>
    {
        /*  Some columns */
    })

 .Editable(editable => editable.Mode(GridEditMode.InLine).CreateAt(GridInsertRowPosition.Top))
 .Pageable(pageable => pageable.Refresh(true).PageSizes(GlobalCode.recordPerPageList).ButtonCount(GlobalCode.PageSize).Input(true).Numeric(true))
                             .HtmlAttributes(new { @class = "dynamicWidth" })
            .Sortable(sorting => sorting.Enabled(true))
                             .Render();
                        }

So when I click on first time on "Add New Record" button it will add new row like below

enter image description here

Now I again click on "Add New Record" button it will add another row in the grid as shown below:

enter image description here

I do not want to add new row when there is already row available in the grid for new record.

Radiobutton Selected value not pass to the controller

I have 2 radio buttons with mvc view.When i do form submit that Checkboxes values not pass to the controller.

I have a form submit like this,

@using(Html.BeginForm("Index","Employee",FormMethod.Get))
{
    <b>Search by :</b>@Html.RadioButton("Searchby", "EmpName",true)<text>Name</text>
    @Html.RadioButton("Searchby", "IsPermanant")<text>Id</text><br />
    @Html.TextBox("Search");
   <input type="submit" value="Search" />
}

I have a controller

public ActionResult Index(string Search, bool Searchby)//In here searchby is null
{

}

Multiselect list in Kendo Grid inline editing

I need to use multiselect list in kendo grid (inline editing) so that user can select multiple values from the list per row.

Following are my requirements: 1. At the time of display, kendo grid should show comma separated list of all the selected values. 2. At the time of Add, kendo grid should show multiselect list and allow to select multiple values. 3. At the time of Edit, kendo grid should show multiselect list with already selected values. User should be able to modify the select and add/remove items from the list.

When user clicks on update/save button, selected values from multiselect list should be available in code behind (in update ajax action) along with id of row.

Following what I do as of now:

I am taking an approach similar to using a drop down list in kendo inline grid. I have created an Editor Template for displaying multiselect at the time of add/edit.
Following is the code:

@model List @using Kendo.Mvc.UI

@(Html.Kendo().MultiSelectFor(c=>c)

      .Name("company_connector_id")
      .DataTextField("connector_name")
      .DataValueField("company_connector_id")
      .Placeholder("Select connector...")

              .AutoBind(false)
                        .Value((List<int>)ViewData["SelectedValues"])
                .DataSource(source =>
                {
                    source.Read(read =>
                    {
                        read.Action("GetCompanyConnectors", "BrandConnector");
                    })
                    .ServerFiltering(true);
                })
           )
@Html.ValidationMessageFor(m => m)

Explanation: I bind a list of model class to the multiselect and set data source in the read action. For selecting the selected values at the time of edit, I have created a function that returns the ids of selected values and put that in View Data in the read action.

I've used this Editor template in my Index page as following code:

@{Html.Kendo().Grid<Cee.DomainObjects.DomainObjects.BrandConnector>()
.Name("BrandConnectorGrid")
.Filterable()
.Events(e => e.Edit("onEdit"))
.DataSource(dataSource => dataSource
.Ajax()
.Events(e => e.Error("error_handler").RequestEnd("onRequestEnd"))
.ServerOperation(false)
.Model(model =>
{
  model.Id(p => p.brand_id);
  model.Field(e => e.CompanyConnectorList).DefaultValue(new 
  List<Cee.DomainObjects.DomainObjects.CompanyConnector>());
})
.Read(read => read.Action("_AjaxBinding", "BrandConnector",new{companyID = 0 }).Type(HttpVerbs.Post))
.Update(update => update.Action("_UpdateBinding", "BrandConnector").Type(HttpVerbs.Post)))
                               .Columns(columns =>
                               {
                                   columns.Bound(c => c.brand_connector_id).Width(0).Hidden(true);
                                   columns.Bound(c => c.company_id).Width(0).Hidden(true);
                                   columns.Bound(c => c.brand_id).Width(0).Hidden(true);
                                   columns.Bound(u => u.brand_name).Title("Brand").Width("18%").HtmlAttributes(new { @class = "brkWord", @readonly = "readonly" });
                                   columns.ForeignKey(u => u.connector_name, Model.CompanyConnectorList, "company_connector_id", "connector_name").Title("Connector").Width

("16%").HtmlAttributes(new { @class = "brkWord"     }).EditorTemplateName("company_connector_id");
 columns.Command(p => p.Edit().Text("Edit").HtmlAttributes(new { @title = "Edit" })).Width("16%").Title("Edit");
                               })
.Editable(editable => editable.Mode(GridEditMode.InLine).CreateAt(GridInsertRowPosition.Top))
                            .Pageable(pageable => pageable.Refresh(true).PageSizes(GlobalCode.recordPerPageList).ButtonCount(GlobalCode.PageSize).Input(true).Numeric(true))
                                                        .HtmlAttributes(new { @class = "dynamicWidth" })
                                       .Sortable(sorting => sorting.Enabled(true))
                                                        .Render();
                            }

Explanation: I've used ForeignKey. Bound it to the string column "connector_name". Connector_name is a comma separated list of IDs that I send from controller. Editor template is used here.

Issue: It works fine at the time of View/Display in Index but Edit does not show selected value. Also we do not get updated value in code behind on update click.

Is this correct way of implementing multiselect list or do I need to bind a collection property as a column in grid? If I bind a collection property as a column then how would I be able to show comma separated string at the time of display?

Regards, Rahul

How to unit test this .net MVC function?

I have this function and unit test.

ProfileController Code

[HttpPost]
public ActionResult Edit(int? id)
{
  var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile", new { id = 0 });
  return Json(new { Url = redirectUrl });
}

unit test code

[TestMethod]
public void TestDetailsViewData()
{
    var controller = new ProfileController(_Profile); 

    var result = controller.Edit(1) as ViewResult;
    var profile = (VIEWMODELS.Customer.Profile)result.ViewData.Model;
    Assert.AreEqual("Testor", profile.cardName);
}

i would like to test this function and this function will redirect to index page and return ViewPage with data. But the problem is when i run this unit test code i got Null exception at this line ,because of the Request is NULL

var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile", new { id = 0 });

so may i know how could i test this?

Full Calendar Time Range Selection

Can some one tell me how to achieve something like below image. How can i select particular time range in selected days. I am using full Calendar jquery library.

enter image description here

Unity.Mvc3 vs Unity.Mvc

Using the Unity.Mvc3 with a Mvc 3 application, i could register my IDummyService as follows:

container.RegisterType<IDummyService, DummyService>(new HierarchicalLifetimeManager());

On each web request, a new instance of my IDummyService is created (as explained in this article), but since I upgraded Mvc 3 to Mvc 4 and hense Unity.Mvc3 to Unity.Mvc, an single instance is created and used across all web requests, untill restarting the app. Basically, IDummyService is a singleton in a Mvc 4 application when using HierarchicalLifetimeManager. For me this is hard to believe this is intended new behavior in Unity.Mvc.

Is there a better explanations for this?

How to genrate or create MS-Word file using open XML in ASP.NET MVC 4?

I have a string from which i want to create doc file.I want to create MS-WORD file using open XML because it is recommended to use open XML on web based applications.

Cannot connect to database getting error 26

I have been trying to do the MVCMusic Store Project. I have created a project and connected to one database fine. I have the database for the mvc music store project in my server explorer and can open it. However, whenever I try to create a user it tells me it cannot connect. Error is below.

Server Error in '/' Application. A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) 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.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Source Error:

Line 80: // Attempt to register the user Line 81: MembershipCreateStatus createStatus; Line 82: Membership.CreateUser(model.UserName, model.Password, model.Email, "question", "answer", true, null, out createStatus); Line 83: Line 84: if (createStatus == MembershipCreateStatus.Success)

Source File: c:\projects\Bricks\Bricks\Controllers\AccountController.cs Line: 82

Stack Trace:

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5340655 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5350915 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +922 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +518 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5353725 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +38 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +732 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +85 System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1057 System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78 System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +196 System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +146 System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +16 System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) +94 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) +110 System.Data.SqlClient.SqlConnection.Open() +96 System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +88 System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +239 System.Web.Security.SqlMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) +2456 System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) +207 Bricks.Controllers.AccountController.Register(RegisterModel model) in c:\projects\Bricks\Bricks\Controllers\AccountController.cs:82 lambda_method(Closure , ControllerBase , Object[] ) +104 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +156 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27 System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +50 System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +225 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +28 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690172 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

ASP.NET Boilerplate Module Zero AbpAuthorize not working and /AbpScripts/GetScripts returns sever error

I just started developing a web application using ASP.NET Boilerplate Framework. Until I tried to implement authorization using module zero, it was working just fine. But now when I run the the web app it seems it is ignoring the AbpAuthorize attribute.

[AbpAuthorize]
public class DashboardController : MyWebAppControllerBase
{
    // GET: Dashboard
    public ActionResult Index()
    {
        return View("~/App/Main/views/layout/layout.cshtml");
    }
}

Also /AbpScripts/GetScripts returns

Method not found: 'System.Collections.Generic.IReadOnlyList`1<Abp.Authorization.Permission> Abp.Authorization.IPermissionManager.GetAllPermissions()'.

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.MissingMethodException: Method not found: 'System.Collections.Generic.IReadOnlyList`1<Abp.Authorization.Permission> Abp.Authorization.IPermissionManager.GetAllPermissions()'.

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.

Stack Trace: 


[MissingMethodException: Method not found: 'System.Collections.Generic.IReadOnlyList`1<Abp.Authorization.Permission> Abp.Authorization.IPermissionManager.GetAllPermissions()'.]
   Abp.Web.Authorization.<GetScriptAsync>d__2.MoveNext() +0
   System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start(TStateMachine& stateMachine) +70
   System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start(TStateMachine& stateMachine) +14
   Abp.Web.Authorization.AuthorizationScriptManager.GetScriptAsync() +128
   Abp.Web.Mvc.Controllers.<GetScripts>d__0.MoveNext() +346
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
   System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651188
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212

What am I missing here? I tried to implement everything on the Module Zero sample project but it seems there is something I am missing.

Cfdump equivalent in ASP.NET MVC 5

I need help learning to debug ASP MVC 5 apps. I'd like to be able to spit out the values of variables at any time the way you can with cfdump in ColdFusion. Is this possible?

Implementing bound dropdown list in MVC5 - Post action returns null values

I appear to be having some problems with dropdown list populating and binding in MVC. The simple example I have has a List of Movies with a Genre item that is populated with a drop down.

I pass across a Select List with the items to populate the drop down but appear to be running into problems when the post action is happening.

The problems appear to be : The ViewModel being returned appears to return the GenreList as null on the Post action. The Genre does not appear to be set so that after the edit -the dropdown list is populated correctly.

I cannot seem to find a good answer for this and have been trying quite a few examples but seem to be going round in circles. Would like to try and get this most basic of dropdown list edit example working so I can see how this should be implemented.

Model Classes

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace Test.Models
{
public class Genre
{
    [Key]
    public int Id { get; set; }
    public string Description { get; set; }
}


public class Movie
{
    [Key]
    public int MovieID { get; set; }

    public string Name { get; set; }


    public Genre MovieGenre { get; set; }
}

public class MovieViewModel
{
    public Movie MovieItem { get; set; }
    public SelectList GenreList{ get; set; }

}
}

Controller Code

namespace Test.Controllers
{
    public class MoviesController : Controller
    {

        private DataContext _dc = new DataContext();

        // GET: Movies
        public ActionResult Index()
        {
            var x = from m in _dc.Movies
                    select m;

            return View(x.ToList());
        }

        // GET: Movies/Edit/5
        public ActionResult Edit(int id)
        {

            var x = from m in _dc.Movies
                    where m.MovieID == id
                    select m;

            var l = from m in _dc.Genres
                    select m;

            var y = new MovieViewModel
            {
                GenreList = new SelectList(l.ToList(), "ID", "Description"),
                MovieItem = x.FirstOrDefault()
            };

            return View(y);
        }

        // POST: Movies/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, MovieViewModel m)
        {
            // PROBLEM: GenreList in model is now not populate for return

            if (ModelState.IsValid)
            {

                var movie = _dc.Movies.Find(id);
                movie.Name = m.MovieItem.Name;
                movie.MovieGenre = m.MovieItem.MovieGenre;
                // PROBLEM: The MovieGenre does not appear to be saved correctly 
                //          when you make the edit and go back to that record after saving
                //          the dropdown is not populated.
                _dc.SaveChanges();
                return RedirectToAction("Index", "Movies");
            }



            return View(m);
        }


    }
}

Razor View Code

@model Test.Models.MovieViewModel

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>


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

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

        <div class="form-group">
            @Html.LabelFor(model => model.MovieItem.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.MovieItem.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.MovieItem.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div>
                @Html.LabelFor(m => m.GenreList, "Genre:")
                @Html.DropDownListFor(m => m.MovieItem.MovieGenre.Id, (IEnumerable<SelectListItem>) Model.GenreList)


            </div>
        </div>

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

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

Duplicated data in MVC linq query

I have a question regarding linq query. My controller code looks like this:

public ActionResult Show_Trans(int id = 0)
    { 
        //this checks if the id exists in the database
        var check = db.Student_Trans.Where(s=>s.student_id == id).FirstOrDefault();
        // if not, show a javascript alert
        if(check == null){
            return Content("<script type='text/javascript'>alert('No transaction so far.');</script>");
        }

        // this return the data that equals to the id
        return PartialView(db.Payments_vw.Where(s=>s.student_id == id).ToList());

    }

In my database view (Payments_vw), for example, the student with student id of 2 has 3 transactions namely: Miscellaneous, Parents Share, Uniform.

The question is: when I tried to view it in my Views, it returns the exact number of rows but the datas are repeated or should I say, all are in Miscellaneous transaction but the Parents Share and Uniform are not shown. Why? Any help is greatly appreciated. Thanks.

Here is my view:

@model IEnumerable<Billing_App.Models.Payments_vw>

<h3><b>List of Transaction Logs</b></h3>
<table class="table">
<tr>
    <th>Student Name</th>
    <th>Transaction Name</th>
    <th>Transaction Amount</th>
    <th>Amount Paid</th>
    <th>Deadline</th>
    <th>Remaining Balance</th>
</tr>
@foreach (var item in Model)
{ 
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.student_lastname)&nbsp;, @Html.DisplayFor(modelItem => item.student_firstname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.trans_name)
        </td>
        <td>
            P &nbsp; @Html.DisplayFor(modelItem => item.trans_amount)
        </td>
        <td>
            P &nbsp; @Html.DisplayFor(modelItem => item.payment)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.trans_deadline)
        </td>
    </tr>

}

I think there's something wrong with my linq query.

EF in.NET, Layers DTO DAL DAO

I'm real confused about layers in .NET so i'm looking for some explanations for each of the following. DTO(how does it transfer an obeject from DAL to BL?) DAL DAO, BO/BL(are the same?). What does each of those layer should contain and what is the relation between each other. Where does repository pattern should be implemented and what exactly is the repository pattern is CRUD a repo?. where does CRUD operation should be implemented in BL or DAL? What is a DOMAIN "The domain will be modelled by the Entity Framework upon the tables found in the database", ok so if i'm using code first?. I'm looking for simple explanations and simple pieces of code especially for DTO / DAL and DAO, for which i'm the most confused upon. I've read articles viewed tutorials but it didn't filled my gape. In which layer does EF belong? Why is it a good practice to put your models in in both a different class library and in the Model folder in the MVC.

How do I tell Resharper to look in a custom location for Partial views?

I have set up a project that has a custom ViewEngine that changes the traditional locations that Partials can be located. Previously, Resharper would let me F12 into my partial views, but that no longer works because Resharper thinks they don't exist even though they do. Can I do something to let Resharper know where to look for these files?

asp.net MVC 2 view with slow UI responsiveness

my web application MVC view displays a grid of records, some of which the user can select and post their data back to the server. As long as the record count is in the order of multiples of dozens, the page is responsive. Problems occur when the records are in the order of a thousand and a half. I've experienced two kinds of problems, one in chrome, one in IE 11. First of all the query to retrieve the records from the DB is kind of slow, but acceptable, let's say that after 5=10 seconds the controller will call a "return view()" passing a model which is a collection of about 1500 records. Then this happens in Chrome: the browser renders the page quick enough considered the number of record, but after that the page becomes unresponsive in all its elements: as an example, consider the to activate a checkbox, it takes about 10 seconds before you see the check mark after you clicked. In IE11 this happens instead: the page hangs for about three minutes between the jquery method "document.ready" and its anonymous handler function. After that the page renders all its elements and its responsiveness is acceptable. My Application is developed in MVC2, and besides jquery, it uses datatables to display the grid, together with bootstrap for styling. Every record has about 20 fields so the page will have 20 form controls (input type=hidden) to post back for each selected record. Considering nothing of that matter happens when I'm retrieveing few records, can you help me understand what's going on and how I can give performance to my web page? Thanks in advance......

Which DataType should be used for Editor & File and image browser

Which datatype should be used in MSSQL database with an MVC application for the following fields as on the following components? http://ift.tt/1chOLhe

  • Editor & File
  • Image browser

MS MVC 4(VB) -batch post to ajax with json string

I'm another newbie to Microsoft MVC. I'm also using VB.NET. I have a CRUD app when I'm trying to write a batch update. Meaning loop though my HTML Table, find out if modified and POST to my MYSQL table.

I get two errors 1.) db.Entry(model).State = EntityState.Modified in my controller says "entitiy type List'1 not in my model" 2.) if I change one of my table fields to "EditorFor" because I want to edit that field my code doesn't pick up my changes only what was initially loaded to the table.

Any pointers would be appreciated

My MODEL

Namespace Models
Public Class Tickets
    <Display(name:="id")> Public Property id As Nullable(Of Integer)
    <Display(name:="status")> Public Property status As Nullable(Of Integer)
    <Display(name:="bug id")> Public Property bug_text_id As Nullable(Of     Integer)
    <Display(name:="build")> Public Property build As String
    <Display(name:="Summary")> Public Property summary As String
    <Display(name:="priority")> Public Property priority As Nullable(Of Integer)
End Class



My CONTROLLER VB
<HttpPost> _
Public Function Update(model As List(Of EFMySQLCrud10.Models.Tickets)) As ActionResult
    '
    Dim pta_Value = New Models.Tickets
    For Each item In model
        If item.id = item.id Then
            pta_Value = item
            If ModelState.IsValid Then
                db.Entry(model).State = EntityState.Modified
                db.SaveChanges()
            End If

            'Exit For
        End If
    Next

    'Return View(pta_Value)
    Return RedirectToAction("Index")
End Function

MY JS which is in my VIEW for now JS in my VIEW window.gbDataURL = '@Url.Action("Update", "PTA")';

    function batch_Save() {


            var table = document.getElementById('results');


       //setup model array
            model = [];


            ////
            //loop view table for values
            for (var i = 1; i < table.rows.length; i++) {
                var str_priority_id = (table.rows[i].cells[0].innerHTML);
                var str_priority = (table.rows[i].cells[1].innerHTML);
                var str_status = (table.rows[i].cells[2].innerHTML);
                var str_bugId = (table.rows[i].cells[3].innerHTML);
                var str_build = (table.rows[i].cells[4].innerHTML);


                //build jSON model
                var item = { id: str_priority_id, priority: str_priority };
                model.push(item);
            }


            $.ajax({
                url: gbDataURL,
                data: JSON.stringify(model),
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    //call is successfully completed and we got result in data
                    alert("ajax call was successful")

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    //some errror, some show err msg to user and log the error
                    alert(xhr.responseText);

                }
            });

        }

Could not run asp.net mvc 6 on Docker

I followed the guidance at Visual Studio Code to create an ASP.NET MVC app. I can run it on my local (windows 8). But when I tried to publish it to Docker, and the problem happened.

My dockerfile like

FROM microsoft/aspnet:1.0.0-beta4

#install npm in docker image
RUN apt-get update && apt-get install -y curl
RUN curl -sL http://ift.tt/1oa11OK | bash -
RUN apt-get install -y nodejs

#install bower and grunt
RUN npm install -g bower
RUN npm install -g grunt-bower-cli
RUN npm install -g grunt
RUN npm install -g grunt-cli
RUN npm install -g grunt-bower-task

COPY project.json /app/

WORKDIR /app

RUN ["dnu", "restore"]

COPY . /app

CMD ["cd", "/app/"]
CMD ["npm", "install"]
CMD ["bower", "install"]

EXPOSE 5001

ENTRYPOINT ["dnx", "kestrel"]

Then I tried to build it

docker build -t thangchung/webdemo .

and

docker run -i -p 8080:5001 -t thangchung/webdemo

the problem when I run above code, it always threw exception

System.InvalidOperationException: Unable to resolve project 'kestrel' from /app/kestrel
  at Microsoft.Framework.Runtime.ApplicationHostContext..ctor (IServiceProvider serviceProvider, System.String projectDirectory, System.String packagesDirectory, System.String configuration, System.Runtime.Versioning.FrameworkName targetFramework, ICache cache, ICacheContextAccessor cacheContextAccessor, INamedCacheDependencyProvider namedCacheDependencyProvider, IAssemblyLoadContextFactory loadContextFactory, Boolean skipLockFileValidation) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.Runtime.DefaultHost.Initialize (Microsoft.Framework.Runtime.DefaultHostOptions options, IServiceProvider hostServices) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.Runtime.DefaultHost..ctor (Microsoft.Framework.Runtime.DefaultHostOptions options, IServiceProvider hostServices) [0x00000] in <filename unknown>:0
  at Microsoft.Framework.ApplicationHost.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder,
 System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0

Could anyone let me know why I could not run it on Docker?

Any suggestion is welcome. Thanks.

Url rewrite in MVC

i work at a MVC application and i want to make url's more friendly. i was trying to do that using routes but at some url's it doesn't work.

i want a url like http ://localhost:55696/fr/Pages/Lists?pageType=PropertiesList&list=Market to become http: //localhost:55696/fr/(market_in_french)

I was trying with

routes.MapRoute(
    name: "MarketFr",
    url: UrlStrings.ResourceManager.GetString("Market", new CultureInfo(CultureEnum.fr.ToString())),
    defaults: new {controller = "Pages", action = "Lists"}
);

but the result is http://localhost:55696/fr/market?pageType=PropertiesList&list=Market

how can I solve this. The Lists method is defined like this:

public ActionResult Lists(string pageType, string list = "", string viewType = "")

Visual Studio Code With ASP.NET MVC Project

I just downloaded Visual Studio Code and try for a couple hours as common editor, and it works really amazing. But when I want to open my currently running ASP.Net MVC Project, it doesn't detect the project as working project, that I can't use the InteliSense provided for C#.

Can I open the ASP.Net MVC Project that created from Visual Studio? If can, then what should I do in order to achieve this?

How can we debug web application on Visual Studio Code?

Microsoft just released Visual Studio Code a couple of days ago.

How can we debug ASP.NET MVC applications from within that IDE?

Integreting Google Maps to ASP.NET MVC 5 Framework using JavaScript

Hi everybody I have a question about Asp.Net Mvc 5. I want to show to user the closest pharmacies, markets, gyms etc. I have found an example about this but it is for just Liverpool. And this version is just for Liverpool I want this: A user will create his/her profile and certainly address. from his/her address, My website should find closest places like markets, restaurants etc.

     @{
    ViewBag.Title = "Home Page";
    }


     <script src="http://ift.tt/UE5hJi" type="text/javascript"></script>

     <!-- This css is to ensure that the google map contols (zoom bar etc) show and size correctly. -->
     <style>
     #map_canvas img{max-width:none}
     </style>

     <!-- This css is to give a nice big popup "info window" when a marker is clicked on the map -->
     <style>
     .infoDiv {
     height: 200px;    
     width: 300px; 
    -webkit-user-select: none; 
    background-color: white; 
    }
    </style>

    <!-- This is the div that will contain the Google Map -->
    <div id="map_canvas" style="height: 600px;"></div>

     <!-- Enclose the Javascript in a "section" so that it is rendered in the correct order after scripts have been loaded etc -->
     @section scripts {
    <section class="scripts">

    <script type="text/javascript">

    <!-- This code tells the browser to execute the "Initialize" method only when the complete document model has been loaded. -->
    $(document).ready(function () {
        Initialize();
    });

    // Where all the fun happens 
    function Initialize() {

        // Google has tweaked their interface somewhat - this tells the api to use that new UI
        google.maps.visualRefresh = true;
        var Liverpool = new google.maps.LatLng(53.408841, -2.981397);

        // These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
        var mapOptions = {
            zoom: 14,
            center: Liverpool,
            mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
        };

        // This makes the div with id "map_canvas" a google map
        var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

        // This shows adding a simple pin "marker" - this happens to be the Tate Gallery in Liverpool!
        var myLatlng = new google.maps.LatLng(53.40091, -2.994464);

        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: 'Tate Gallery'
        });

        // You can make markers different colors...  google it up!
        marker.setIcon('http://ift.tt/1dEZgVV')

        // a sample list of JSON encoded data of places to visit in Liverpool, UK
        // you can either make up a JSON list server side, or call it from a controller using JSONResult
        var data = [
                  { "Id": 1, "PlaceName": "Liverpool Museum", "OpeningHours":"9-5, M-F","GeoLong": "53.410146", "GeoLat": "-2.979919" },
                  { "Id": 2, "PlaceName": "Merseyside Maritime Museum ", "OpeningHours": "9-1,2-5, M-F", "GeoLong": "53.401217", "GeoLat": "-2.993052" },
                  { "Id": 3, "PlaceName": "Walker Art Gallery", "OpeningHours": "9-7, M-F", "GeoLong": "53.409839", "GeoLat": "-2.979447" },
                  { "Id": 4, "PlaceName": "National Conservation Centre", "OpeningHours": "10-6, M-F", "GeoLong": "53.407511", "GeoLat": "-2.984683" }
               ];

        // Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
        $.each(data, function (i, item) {
            var marker = new google.maps.Marker({
                'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
                'map': map,
                'title': item.PlaceName
            });

            // Make the marker-pin blue!
            marker.setIcon('http://ift.tt/1kglguQ')

            // put in some information about each json object - in this case, the opening hours.
            var infowindow = new google.maps.InfoWindow({
                content: "<div class='infoDiv'><h2>" + item.PlaceName + "</h2>" + "<div><h4>Opening hours: " + item.OpeningHours + "</h4></div></div>"
            });

            // finally hook up an "OnClick" listener to the map so it pops up out info-window when the marker-pin is clicked!
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(map, marker);
            });

        })
    }


</script>
</section>
     }

I have no idea about JavaScript and I do not know how to modify this code. Please help me. If there are other ways please inform me.

server.mappath indicate the name of controller

I want to add an image and I concat the server directory with the directory where I want to save the file. But the name of the controller is added in the complete path that I do not want.

                string newFile = "\\Photoclient\\photo\\" + System.IO.Path.GetFileName(Tretouche.fichierphoto.FileName);
                // getting a valid server path to save
                string cheminfichier = Server.MapPath("..") + newFile;
                if (Tretouche.fichierphoto.FileName != String.Empty)
                {
                    Tretouche.fichierphoto.SaveAs(cheminfichier);
                    Tretouche.SRCphoto = "\\Photoclient\\photo\\" + System.IO.Path.GetFileName(Tretouche.fichierphoto.FileName);
                }

there is an error when save file because cheminfichier contains the name of the controller in the path. Tks for help

Responsive design with dynamic image sets

I need to build a page with a header background image that is randomly selected. We want to store the available images in our CMS so I imagine the random selection of the image will occur in server-side code. This page is going to use responsive design and the mobile size will need a smaller version of the same image (but it can't just be the same image scaled down). I.E. if there's a photo of "Bobby" at full width and you shrink your browser to mobile width, a smaller image file of "Bobby" will show, but when you refresh the page, this time a picture of "Lucy" might show. We are ok with using a naming convention to associate the full-size and small images with one another if necessary.

Normally I would expect the CSS, using media queries, to specify the URL to the large image and the URL to the small image. But in this case, the CSS doesn't know ahead of time what the URLs will be. They're chosen dynamically. All we can do is output the URLs to the page. I don't want the client to request an image unless it is displayed though; i.e. if I'm viewing the mobile version, the full-size image shouldn't be downloaded. The solution can use jQuery if necessary but if scripting can be avoided, that's even better. How can I accomplish this?