lundi 29 juin 2015

this dictionary requires a model item of type

learning to work around c# and razor. I have this issue which I am struggling to get my head around. I have researched this forum to understand but to no avail. The model item passed into the dictionary is of type '', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable

Anyway this is the code I have been working with: However my data are coming from my VehicleClass. My VehicleClass

using LogViewer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LogViewer.Classes
{
    public class VehicleClass
    {
        public int id { get; set; }
        public String make { get; set; }
        public String type { get; set; }
        public byte taxBand { get; set; }
        public DateTime created { get; set; }
        public DateTime updated { get; set; }
        public DateTime deleted { get; set; }
        public bool isDeleted { get; set; }
        public decimal price { get; set; }
        public String description { get; set; }

        public List<Vehicles> _VehicleList = new List<Vehicles>();

        public VehicleClass()
        {
            _VehicleList.Add(new Vehicles
            {
                id = 001,
                make = "Renault",
                type = "Saloon",
                taxBand = 5,
                created = new DateTime(2015,1,1),
                updated = new DateTime(2015,3,1),
                deleted = DateTime.Now,
                isDeleted = true,
                price = 3000,
                description = "A very comfortable car to ride"
            });

            _VehicleList.Add(new Vehicles
            {
                id = 002,
                make = "Toyota",
                type = "Hatchback",
                taxBand = 2,
                created = new DateTime(2015,2,1),
                updated = new DateTime(2015,3,9),
                deleted = DateTime.Now,
                isDeleted = true,
                price = 2500,
                description = "Reliable, strong, fuel efficient"
            });

            _VehicleList.Add(new Vehicles
            {
                id = 003,
                make = "Audi",
                type= "Saloon",
                taxBand = 6,
                created = new DateTime(2015,4,3),
                updated = new DateTime(2015,6,1),
                deleted = DateTime.Now,
                isDeleted = true,
                price = 6000,
                description = "A high performance car"
            });
        }
    }
}

Controller Class: HomeController.cs

using LogViewer.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LogViewer.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index(string sortOrder)
        {
            VehicleClass _vehicles = new VehicleClass();
            ViewBag.IdSortParam = String.IsNullOrEmpty(sortOrder) ? "id_desc" : "";
            ViewBag.MakeSortParam = sortOrder == "Make" ? "make_desc" : "Make";

            switch(sortOrder)
            {
                case "id_desc":
                    _vehicles._VehicleList.OrderByDescending(v => v.id).ToList();
                    break;

                case "make_desc":
                    _vehicles._VehicleList.OrderByDescending(v => v.id).ToList();
                    break;

                default:
                    break;
            }
            return View(_vehicles._VehicleList.ToList());
        }
    }
}

Finally my View: Index.cshtml

@model LogViewer.Classes.VehicleClass

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<table>
    <thead>
        <tr>
            <th>
                @Html.ActionLink("ID", "Index", new { sortOrder = ViewBag.IdSortParam, currentFilter = ViewBag.CurrentFilter})
            </th>
            <th>
                @Html.ActionLink("Make", "Index", new { sortOrder = ViewBag.MakeSortParam, currentFilter = ViewBag.CurrentFilter})
            </th>
            <th>Type</th>
            <th>Tax Band</th>
            <th>Created</th>
            <th>Updated</th>
            <th>Deleted</th>
            <th>Is Deleted</th>
            <th>Price</th>
            <th>Description</th>
        </tr>
    </thead>
</table>

@foreach (var item in Model._VehicleList)
{
<table>
    <tbody>
        <tr>
            <td>@item.id</td>
            <td>@item.make</td>
            <td>@item.type</td>
            <td>@item.taxBand</td>
            <td>@item.created</td>
            <td>@item.updated</td>
            <td>@item.deleted</td>
            <td>@item.isDeleted</td>
            <td>@item.price</td>
            <td>@item.description</td>
        </tr>
    </tbody>
</table>
}

The error I have been receiving is this:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[LogViewer.Models.Vehicles]', but this dictionary requires a model item of type 'LogViewer.Classes.VehicleClass'.

The name does not exist in the current context (in ActionResult with MVC Entity Framework)

In ActionResult "Details(int? id)" of a controller I have:

            var TheUser = db.AspNetUsers.Where(u => u.Id == CurrentUser)
                         .Select(u => new
                         {
                             ID = u.Id,
                             Email = u.Email,
                             Username = u.UserName,
                             Surrname = u.Surname,
                             Name = u.Name,
                             Role = u.Role,
                             CreditBalance = u.CreditBalance
                         }).Single();

            var TheJournal = db.CreditJournal.Where(tj => tj.CvID == id && tj.UseBy == CurrentUser)
                            .Select(tj => new
                               {
                                   IdJournal = tj.IdJournal,
                                   Operation = tj.Operation,
                                   CvID = tj.CvID,
                                   CreditConsumed = tj.CreditConsumed,
                                   UseDate = tj.UseDate,
                                   UseBy = tj.UseBy
                               });

            var Counter = TheJournal.Count();

When I evaluate values in Debug Mode I have:

TheUser |>>>    { ID = "56cc2430-4db5-4799-ad41-fa1d103d1967", Email = "sales@maps4u.ro", Username = "sales@maps4u.ro", Surrname = "Laurentiu", Name = "LAZAR", Role = 3, CreditBalance = 75 }  <Anonymous Type>

TheJournal |>>> {System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>>}  System.Linq.IQueryable<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>> {System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>>}

Counter |>>>    The name 'Counter' does not exist in the current context

What can be wrong in simple code from above? (The equivalent SQL statement for TheJornal returns for the given criteria, at least 4 records). Somehow I think to declare the variables outside the condition, but what type have to be? (Anyway the first, TheUser is just ok, the issue start with second, TheJournal )

Approach for encrypting user data with user password

I have the following requirement: Users on my site have some sensitive data, meaning that ONLY the owner user should be able to read it. In other words: I have to make sure that not even the site/sql administrators can (human) read the content.

I am trying to implement the following approach: When saving the data, encrypt it by using the user password. When serving the data to the user, decrypt it using the user's password. I can handle the password-change scenario by re-encrypting the user data. However, the issue is that the only time I have the user password is during Loging-In and I am not sure it's a good idea to 'hold on to it' by storing it in the user profile in-mem object.

So, how would I go about such requirement? Again - the goal is that only the user should be able to en/decrypt their data on the fly. Any tips appreciated.

Fresh MVC project is giving 500 error for RequestFilteringModule

Hi I am getting following error for a fresh MVC project. Any idea how to fix it? 500 error

Title for Anchor tag with condition check in MVC

This code is showing Title on Mouse hover for Anchor tag even my div status is Locked, but I want to show Title for Anchor tag only when div status is not locked. Can anyone assist me to implement this?

 <div>
                <a <% if (!Model.ReservationStatus.IsPrintContractLocked){%> href="<%= Url.SignatureFormAction() %>"
                    <% }%> title=" <%= Html.Encode(Model.ReservationStatus.IsPrintContractComplete ? Resources.Edit : Resources.EnterInfo)%> <%=Resources.SignatureForm%>"><span class="accessibleText">
                        <%=Resources.SignatureForm%></span>
                    <div class="status<% if (Model.ReservationStatus.IsPrintContractComplete){%> complete<% }%><% if (Model.ReservationStatus.IsPrintContractLocked){%> locked<% }%>">
                    </div>
                    <div status="<%= Model.ReservationStatus.IsPrintContractComplete%>" locked="<%= Model.ReservationStatus.IsPrintContractLocked%>">
                        <%=Html.Encode(Model.ReservationStatus.IsPrintContractLocked ? Resources.Locked : (Model.ReservationStatus.IsPrintContractComplete ? Resources.Completed : Resources.Incomplete))%>
                    </div>
                    <div>
                        <% if (!Model.ReservationStatus.IsPrintContractLocked)
                           {%>
                        <%= Html.Encode(Model.ReservationStatus.IsPrintContractComplete ? Resources.Edit : Resources.EnterInfo)%>
                        <%} %>
                    </div>
                </a>
            </div>
        </div>
    </div>

ASP.NET MVC Ajax will only update first in list

I have a list of Posts in my index page, where you can vote up and down on each one. My problem is that I can only vote on the first one in the list.

My JS:

<script type="text/javascript">
    $(document).ready(function () {
        function voteAjax(pid, vurl, value) {
            // Show a loading gif or something
            // $(".loading").show(); .hide();
            $.ajax({
                url: vurl,
                type: "GET",
                data: { vote: value, id: pid },
                success: function (data) {
                    if (data.success) {
                        // All went well, say thanks
                        $('#vote-display').html(data.displayValue);
                    } else {
                        // show ex error
                    }
                },
                error: function (err) {
                    // the call thrown an error
                },
                complete: function () {
                    // Hide loading gif
                }
            });
        }
        $('#vote-up').click(function () {
            var pid = $(this).attr("data-pid");
            var value = 1;
            var vurl = '@Url.Action("VotePost", "Services")';

            $.ajax({
                url: vurl,
                type: "GET",
                data: { vote: value, id: pid },
                success: function (data) {
                    if (data.success) {
                        // All went well, say thanks
                        $('#vote-display').html(data.displayValue);
                    } else {
                        // show ex error
                    }
                },
                error: function (err) {
                    // the call thrown an error
                },
                complete: function () {
                    // Hide loading gif
                }
            });
        });
    });
</script>

and my view where I display the posts in a list:

@foreach (var post in Model.Posts)
{
    <div class="row">
        <div class="col-md-1 vote-i">
            <a id="vote-up" data-pid="@post.PostID" class="glyphicon glyphicon-chevron-up vote-up"></a><br />
            <span id="vote-display">@Html.DisplayFor(modelPost => post.Vote.Value)</span><br/>
            <a id="vote-down" data-pid="@post.PostID" class="glyphicon glyphicon-chevron-down vote-down"></a><br/>
        </div>
    </div>
}

I suspect there is something going on when I get the postID and that Im only able to get the first one for some reason, but I can't figure it out.

ASP.NET ValidationMessage validate false my double number

I am using NET MVC, EF 6, Entity Data Model to build a site.This page is "Create Sach In the DB, Table Sach, which have fields: Dai, Rong, Cao as float. When running it's allow only int input enter image description here

EF generated class:

But when debug, I enter 1.2 and 1,2, both value are not valid, though they are double! enter image description here

how can I dynamically change the image path in my POPOVER when I change my page in MVC?

I want to change this path "Images/mapCompany.jpg" dynamically when user click on every link in my page

it just work on default page or home page.

html code:

<span id="mapshowing" class="label label-default" data-toggle="popover" data-trigger="hover" data-placement="top" title="Test Title">TEST</span>

javascript code:

function MapPOContent() {
    var mapCompany = "Images/mapCompany.jpg";
    var popOverContent = "<img class='center-block' src=" + mapCompany + " alt='logo' />";
    return popOverContent;
}

$('#mapshowing').popover({
    html: true,
    trigger: 'hover',
    placement: 'top',
    content: function () { return MapPOContent(); }
});

and if user goes to this path it doesn't show any thing in popover "/Home/Contact"

HTTPPost Call through application/x-protobuf Format Not Working

I am using application/x-protobuf format with WebAPi. My Get Request is working fine but when I want to send Post my request (like city data) is not hit the target api action. Please have a look at where I am going wrong Web project

WebAPi

My Cofig Route

PUT methods not working on IIS8

I am having difficulties to run my MVC application on Windows 8 and IIS 8. Whenever I try to call a MVC PUT method the browser UI hangs. The GET method works fine. The network tab in IE developer tools shows the request is pending but no errors. I removed the WebDav module/handler from IIS and changed the applicationhost.config to allow PUT and DELETE but nothing worked. Previously I was using windows7 and everything worked properly and now I have upgraded to Windows8 with IIS 8 and all my PUT methods seems to be not working. Please see the screenshot of developer tools after I hit the Save method. Please let me know how do I enable the PUT requests to allow the save method. enter image description here Thanks,

Deepak

Running a .NET 4.6 MVC application on IIS 8.5 (Windows Server 2012)

I have an MVC Web API 2 application that I am running quite successfully locally within Visual Studio 2015 RC. I have also successfully published this application to an IIS 8.5 instance running on Windows Server 2012. I have installed .NET Framework 4.6 on this machine also.

The behaviour that I am getting when I try to navigate to the root of the site (http://localhost:81) is that I get a directory listing of the files in the root folder. Clearly I was expecting the routing config of the application to kick in an execute the home controller, but this is not happening.

I am a developer and it has been some time since I configured IIS, but I do remember that I had to do some fiddling with IIS (6?) to get the routing to work.

What am I missing?

Model binder in Invariant mode

How to configure mvc model binder to make it work in invariant mode? that's the problem

The only solution that managed to find - is to write your own model binder. But is it possible to make a standard work in the invariant mode?

EDIT An example of a custom binder for decimal numbers.

public class DecimalModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, 
    ModelBindingContext bindingContext) {
    ValueProviderResult valueResult = bindingContext.ValueProvider
        .GetValue(bindingContext.ModelName);
    ModelState modelState = new ModelState { Value = valueResult };
    object actualValue = null;
    try {
        actualValue = Convert.ToDecimal(valueResult.AttemptedValue, 
            System.Globalization.CultureInfo.InvariantCulture);
    }
    catch (FormatException e) {
        modelState.Errors.Add(e);
    }

    bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
    return actualValue;
}

}

Is it possible to do without it ? Set up the standard mvc binder to work with decimal numbers in the invariant mode.

How to insert breakpoints for knockout using chrome

I would like determine what value my my knockout script are returning because I have a strong feeling some of my knockout variables are returning null. I clicked on the line number then chrome is supposed to step through the code somehow please clarify the process??

thanks

Filter records within dbcontext object

I am using Entity Framework 6 database first approach.

I have three tables:

1.SystemRoles

2.MasterAppMenu

3.EmployeeRoleMenuMappings

A SystemRole can have multiple MasterAppMenu, so this is one to many relationship.

This i am trying to do.

private myEntities entities = new myEntities();
var roleMenuMappings = entities.SystemRoles.Where( x => x.EmployeeRoleMenuMappings.Select(  m => m.MasterAppMenu.ParentMenuId==null  )  );
var roleMenuList = await roleMenuMappings.ToListAsync();
return View(roleMenuList);

I want to filter the records of MasterAppMenu which has null value in field ParentMenuId.

Please tell me how to achieve this, i know it can be done on view side , but i want to do it on controller side only

why my dropzone doesn't work properly

i used this tutorial for create dropzone area in my web application mvc 5.

http://ift.tt/16G8GTc

but when i drag and drop my image, the dropzone layout doesn't work. below is my code:

_layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/dropzonescss")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/dropzonescripts")
    <script type="text/javascript">

        Dropzone.options.dropzoneJsForm = {

            //prevents Dropzone from uploading dropped files immediately
            autoProcessQueue: false,

            init: function () {
                var submitButton = document.querySelector("#submit-all");
                var myDropzone = this; //closure

                submitButton.addEventListener("click", function () {

                    //tell Dropzone to process all queued files
                    myDropzone.processQueue();
                });

            }
        };

    </script>

    @RenderSection("scripts", required: false)
</body>
</html>

Index

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


        <form action="~/Home/SaveUploadedFile" method="post" class="dropzone" id="Dropzone.options.dropzoneJsForm" >
            <div class="fallback">
                <input name="file" type="file" multiple />
                <input type="submit" value="Upload" />
            </div>
        </form>

homecontroller

 public ActionResult SaveUploadedFile()
        {
            bool isSavedSuccessfully = true;
            string fName = "";
            try
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];
                    //Save file content goes here
                    fName = file.FileName;
                    if (file != null && file.ContentLength > 0)
                    {

                        var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));

                        string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");

                        var fileName1 = Path.GetFileName(file.FileName);

                        bool isExists = System.IO.Directory.Exists(pathString);

                        if (!isExists)
                            System.IO.Directory.CreateDirectory(pathString);

                        var path = string.Format("{0}\\{1}", pathString, file.FileName);
                        file.SaveAs(path);

                    }

                }

            }
            catch (Exception ex)
            {
                isSavedSuccessfully = false;
            }


            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        }

BundleConfig add

    bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
             "~/Scripts/dropzone/css/basic.css",
             "~/Scripts/dropzone/css/dropzone.css"));
    bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
             "~/Scripts/dropzone/dropzone.js"));

I have no idea why it behaves this way. The loading part is working properly, but the graphics is wrong and looks like:

enter image description here

Searching an object in a collection via lambda

https://www.youtube.com/watch?v=K1xrlc32Tmw&list=PLJUoF2h8Z-brW94dTZ-ZIOhjFq90_lt5K&index=9

4:25 adds a new object in the lineCollection if product does not exist in lineCollection, but at 24:25 it shows duplicating orders? Did i misunderstood how it works?

http://ift.tt/1HrxeRe

Access Denied using ASP.NET Identity + Facebook Test Users

I am developing an ASP.NET MVC 5 website with facebook external login. Everything works fine with my fb account and other real fb accounts.

Now i am trying to use the Test Users Facebook features like described this http://ift.tt/1NsUzjO

[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
         return RedirectToAction("Login");
    }

I didn't change the ASP.NET template code because, with facebook real accounts, it works well without any changes. With Facebook Test Users the variable loginInfo is null and analyzing the web request with Fiddler i read Access Denied in the URL (I accepted Facebook permissions as usual).

How to add ng-pattern in mvc?

I get an error for ng-pattern...how can i add it in @Html.TextBoxFor? I tried with ng-pattern also but same result...it throw me an error...i know that is for ng-model in mvc i need to use ng_model but for ng-pattern is not working

    div class="form-group">
    <label for="licencenumber" class="control-label col-lg-5 col-md-6">@Html.Label(@Translator.Translate("LICENCE_NUMBER")): <span id="licenceNumberRequired" class="required display">*</span></label>
  <div class="col-lg-7 col-md-6">
  @Html.TextBoxFor(m => m.DocumentNumber, new { @class = "form-control", id = "documentNumber", @maxlength = "13", ng_model="documentNumber",ng_pattern="^/[\w ]+$/" })

    </div>
 </div>

About Mvc routes

I want to set a rule only for defaultController

 routes.MapRoute(
     name: "testDefault",
     url: "Default/{action}/{id}.html",
     defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
 );
 routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { 
          controller = "Test", 
          action = "Show", 
          id = UrlParameter.Optional 
     }
);

However, http://ift.tt/1ds6NNi also can be open ,This is not what I want。Someone can help me?

Populate a mvc5 list?

Right now I can create games under the Games/Create. And I can make a post under Post/Create.

But my problem is that right now my public int GameId { get; set; } gets populated with the items that is in my Game table in my SQL database. Which is just fine that's how I like it.

But I want public string Title { get; set; } to the populated the same way with the values that are in the Game database.

public int GameId { get; set; } gets populated with a droplist with the values that is in my Game tabel.

And as for public string Title { get; set; } I have to enter it manually. I want that to be populated the same way as GameId

This is my Post Model

public class Post
{
    [Key]
    public int PostId { get; set; }

    //URL
    [Display(Name = "URL")]
    [StringLength(80)]
    public string Url { get; set; }
    //User
    [Display(Name = "User")]
    public virtual ApplicationUser User { get; set; }

    //Game
    [Display(Name = "Game")]
    public int GameId { get; set; }
    [Display(Name = "Next Game")]
    public string Title { get; set; }
    public virtual Game Game { get; set; }

    //Time
    private DateTime? _date;
    public DateTime? Date
    {
        get
        {
            if (_date == null || _date.ToString() == "1/1/0001 12:00:00 AM")
            {
                return _date = DateTime.Now;
            }
            return _date;
        }
        set
        {
            _date = value;
        }
    }

And this is my Game Model

    public class Game
{
    [Key]
    public int GameId { get; set; }

    //Game
    [Display(Name = "Game")]
    public string Title { get; set; }

    //User
    [Display(Name = "User")]
    public virtual ApplicationUser User { get; set; }
}

Slickgrid - how to modify id value

I'm just getting to grips with Slickgrid (with an asp.net MVC back end) as a simple start I want to us it as an editing grid for a Key/Value pair of systems settings. I have it working OK for Add, but update works OK unless we edit the key.

Because we have changed the key value it always looks like a new Key/Value pair rather than modifying the existing item. So my question is, how do I let the backend know what item I am modifying ?

I figure I could add an extra field (holding the original id) to the dataview, but I am kind of wondering if I a missing some functionality that makes this easier.

$(function() {
    var grid;
    var columns = [{
        id: "id",
        name: "Name",
        field: "id",
        editor: Slick.Editors.Text
    }, {
        id: "Value",
        name: "Value",
        field: "Value",
        editor: Slick.Editors.Text
    }, ];

    var options = {
        enableColumnReorder: false,
        editable: true,
        enableAddRow: true,
        enableCellNavigation: true,
        autoEdit: false
    };

    var dataView = new Slick.Data.DataView();
    grid = new Slick.Grid("#myGrid", dataView, columns, options);

    grid.setSelectionModel(new Slick.CellSelectionModel());

    grid.onCellChange.subscribe(function(e, args) {
        var row = dataView.getItem(args.row);
        var value = row[grid.getColumns()[args.cell].field];
        var id = row[grid.getColumns()[0].field];

        var data = {
            value: value,
            id: id
        };
        var url = "@Url.Action("Update", "SystemSettings")";

        $.ajax({
            type: "POST",
            url: url,
            data: data,
            dataType: "json",
            success: function(a) {
                if (a.status != "ok") {
                    alert(a.msg);
                    undo();
                } else {
                    alert(a.msg);
                }
                return false;
            }
        });
    });

    grid.onAddNewRow.subscribe(function(e, args) {
        var item = {
            "id": dataView.length,
            "value": "New value"
        };
        $.extend(item, args.item);
        dataView.addItem(item);
    });

    dataView.onRowCountChanged.subscribe(function(e, args) {
        grid.updateRowCount();
        grid.render();
    });

    dataView.onRowsChanged.subscribe(function(e, args) {
        grid.invalidateRows(args.rows);
        grid.render();
    });

    $.getJSON('@Url.Action("GetAll", "SystemSettings")', function(data) {
        dataView.beginUpdate();
        dataView.setItems(data);
        dataView.endUpdate();
    });
});

My requirement is for a grid that allows users to be able to perform all the basic CRUD functions on a database table. So am I going in the right direction with this or should I be doing something different.

Is it possible for cookie to timeout in the middle of operation?

Probably a dumb question.

For example if I create cookie with name Permission, value true, and expires in 3 minutes and I have Attribute [CheckPermission].

[CheckPermission]
public ActionResult test()
{
     //do some shitty process that takes 5 minutes
     var flag = cookie["Permission"];
     //rest of code here
}

Ok so let's say you can only access test method if Permission cookie is set to true, test method contains some shitty process that took around 5 minutes, by the time it's done the cookie is already expired because it was set to expires in 3 minutes. Is this scenario possible or .NET automatically prevent this? If yes, then how do you prevent the cookie to not timeout in the middle of operation?

Thanks

Sorry for bad english

Code first EF 6 One to many to one

I am trying to use GraphDiff to update a hierarchical entity graph.

I have my Availability which has a number of Items, and also a booking which eventually wants to select some of these.

public class Availability{
//...
public virtual List<Item> Items { get; set; }
//...
}

public class Booking{
//..
public virtual List<Item> Items {get;set;}
//..
}

public class Item{
//..
public int ID {get;set;}
//..
}

public class MyContext : DbContext{
    protected override void OnModelCreating(DbModelBuilder modelBuilder){
        modelBuilder.Entity<Booking>().HasMany(b => b.Items).WithOptional(e => e.Booking).WillCascadeOnDelete(false);
        modelBuilder.Entity<Availability>().HasMany(ar => ar.Items).WithOptional(e => e.Availability).WillCascadeOnDelete(false);
    }
}

what I am trying to achieve is, rather than - when I assign an Item to a booking form the availability - EF generating 2 records, it generates a single record with 2 foreign keys in it

the DB table does have 2 foreign key columns in it - and I am updating like this

public ActionResult SaveItems(Availability model){
    Booking b = db.Bookings.Include(bk=>bk.Items).Include(...).singleOrDefault(bk=>bk.ID == model.ID);

    b.Items = model.Items;

    db.UpdateGraph(b, map => map
                        .OwnedCollection(bk=>bk.Items, with => with
                            .OwnCollection(i=>i.ChildList)));
    db.SaveChanges();
}

I am assuming that there is something in the fluent mappings that may be able to make this work, but I cant seem to work it out

I have also tried adding this to the OnModelCreating to no avail.

modelBuilder.Entity<Item>().HasOptional(e => e.Booking).WithMany(b => b.Items).WillCascadeOnDelete(false);
modelBuilder.Entity<Item>().HasOptional(e => e.Availability).WithMany(a => a.Items).WillCascadeOnDelete(false);

is this even possible ?

Dropdownlist in MVC with Where cluase in entities

I am new to MVC. I want to fill Dropdownlist only where Account_Type = "D". Here is my Edit.cshtml

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

And here is my Edit Controller

public ActionResult Edit(int? id)
{
    ViewBag.Account_Code = new SelectList(db.Chart_Of_Account, "Account_Code", "Account_Desc", student.Account_Code);
}

MVC - Passing generic model to a method

I have a function FillPdf() which I am using to fill an editable pdf. For now I have defined its parameter type but I have three different forms each having different model so I want is my this FillPdf() receives the respective model and use its data.How to achieve this.

FillPdf.cs

  public static bool FillPdf(M2HDetail m2HUserDetails)
    {
        try
        {
            if (PdfFileSettingViewModel.M2HAuthorizationFormLocation == null)
                return false;
            var pdfReader = new PdfReader(PdfFileSettingViewModel.M2HAuthorizationFormLocation);
            var sb = new StringBuilder();
            foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
            {
                sb.Append(de.Key.ToString() + Environment.NewLine);
            }
            var newFile = Path.Combine(PdfFileSettingViewModel.TempFolderLocation, string.Format("{0}_{1}.pdf", "M2HForm",SessionItems.UserId));
            System.IO.File.Copy(PdfFileSettingViewModel.M2HAuthorizationFormLocation, newFile);

            var pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));

            var pdfFormFields = pdfStamper.AcroFields;
            var totalFields = pdfFormFields.Fields.Count;

            var myParams = new List<string>();

            #region # SetPdfFields #

            pdfFormFields.SetField("Text1", m2HUserDetails.LastName);
            pdfFormFields.SetField("Text2", m2HUserDetails.FirstName);
            pdfStamper.FormFlattening = false;

            #endregion

            pdfStamper.Close();

            return true;

        }
        catch (Exception ex)
        {
            var files = System.IO.Directory.GetFiles(PdfFileSettingViewModel.TempFolderLocation);
            foreach (var file in files)
            {
                System.IO.File.Delete(file);
            }

            return false;
        }

    }

Caller function

 public ActionResult AuthorizationForm(M2HDetail model)
    {
      var isFillPdfSuccess = PdfFiller.FillPdf(model);
      return View();
     }

Now I want that I can use the same pdf method for my other form like this:

 public ActionResult AuthorizationFormHippa(HippaAuthForm model)
    {
      var isFillPdfSuccess = PdfFiller.FillPdf(model);
      return View();
     }

Also I want that my pdf method could have parameter as model like this:

  public static bool FillPdf(ModelForm model)
{
 }

Please suggest how to achieve this.As I can have more than 3 forms in future and each time I have to write the same method just with different parameter type.

How to retrieve list/rows of values from "select" stored procedure Function , where stored procedure Function is auto generated from Entity Framework

How to retrieve list/rows of values from "select" stored procedure Function , where stored procedure Function is auto generated from Entity Framework

I can't retrieve list of values from Stored Procedure Function,I am stucked in some part of code, where Store procedure Function is Auto Generated using Entity FrameWork
Kindly check the code attached and help me to solve this. Thanks in Advance

create procedure [dbo].[SP_MobileList]
(
@MobileId varchar(50) out,
@MobileName varchar(50) out
)
As
Begin
select @MobileId=MobileId,@MobileName=MobileName from BasicMobileData
END

AutoGenerated Code from Entity Framework

//ModelClass
    public partial class BasicMobileData
    {
        public string MobileId { get; set; }
        public string MobileName { get; set; }
        public string MobileIMEno { get; set; }
        public decimal MobilePrice { get; set; }
    }

//In Context
    public virtual DbSet<BasicMobileData> BasicMobileDatas { get; set; }

    //Here it returns single integer value 
    **public virtual int SP_MobileList(ObjectParameter mobileID, ObjectParameter mobileName)
     {
     return((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("SP_MobileList", mobileID, mobileName);
    }**

Controller Code

     public class MobileController : Controller
    {
    MobileEntities objMobileContext = new MobileEntities();
    BasicMobileData objBasicMobileData = new BasicMobileData();

    #region "ActionMethods"
    public ActionResult MobileDetails()
    {
    ObjectParameter objParMobileId = new ObjectParameter("MobileId",typeof(string));
    ObjectParameter objParMobileName = new ObjectParameter("MobileName", typeof(string));

    //I am Stucked in this part of code
    // this "foreach" will not work since ,autogenerated "SP_MobileList(,)" is returning single integer value"
    foreach(BasicMobileData objBasicMobileData  in objMobileContext.SP_MobileList(objParMobileId,objParMobileName)){}
    return View();
    }
     #endregion        
    }

How to find the difference between two dates in No. of days:Hours:Minutes Format [duplicate]

This question already has an answer here:

How to Find Time Difference between Two dates for example if Date one:06-06-2015 04:10:10 Date Two:10-06-2015 05:12:10 ,Answer should be like 04:01:02. Number of day:- The exact days difference between two date. if days count exceeds 365 years can be added. Final format should be in String. Number of days fields refer the exact day difference between two days.

I tried The below code .

int noofdays=00;
int Hours=00;
int min=00;
if(item.StandardWorkingTime!=null && item.
 noofdays = (int)(d1.Subtract(d2)).TotalDays;
 Hours = (in)(d1.Subtract(d2)).TotalHours;
 min=(int)(d1.Subtract(d2)).TotalMinutes;

but it gives error. can anyone please help to me to find the solution.

MVC Model Validation From Database

I have a very simple Model, that needs to get validated from Database

public class UserAddress
{
    public string CityCode {get;set;}
}

CityCode can have values that are only available in my database table.

I know i can do something like.

[HttpPost]
public ActionResult Address(UserAddress model)
{
    var connection = ; // create connection
    var cityRepository = new CityRepository(connection);

    if (!cityRepository.IsValidCityCode(model.CityCode))
    {
        // Added Model error
    }
}

This seems very WET as I have to use this model at lot of placed and adding the same logic each place seems like i am not using MVC Architecture properly.

So, what is the best pattern to validate model from Database ?

NOTE: Most of the validation are single field lookup from Database, other validation may include combination of field. But right now I am happy with single field lookup validation, as long as it is DRY and is not using too much reflection it is acceptable.


P.S. If any one can hint me how to do a attribute based validation from Database, will be extremely greatful, and a bounty will be awarded.

Error on Calling Connection String Define on Web.config [duplicate]

This question already has an answer here:

I have been scrolling on the answers related to my problem. I also tried the upvoted answers but still Im having the same error. I already installed the mysql connector and added in the reference. And I could not figure out why is this happening. Please help.

My Web.config file connection string look like:

<configuration>

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

  <connectionStrings>
    <add name="Dbconnection"
         connectionString="Server=localhost; Database=dbtest;Username=root;Password=password;Integrated Security=True"
         providerName="Mysql.Data.MySqlClient" />
  </connectionStrings>

</configuration>

And I am trying to call to in my Controller(just to check) this way:

using System;
using System.Collections.Generic;

using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using MySql.Data.MySqlClient;

public ContentResult checkConn()
{
    MySqlConnection cnn = new MySqlConnection();
    cnn.ConnectionString = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString; 
    return Content(cnn.ConnectionString);
}

I am getting an error prompting: "Object reference not set to an instance of an object."

assembly not found && deploy asp.net mvc application

I have an Asp.net mvc application in which I have used Telerik.OpenAccess tool then I deleted it.

When I launch my application it runs without errors! But when I deploy it I get this error :

Could not load file or assembly 'Telerik.OpenAccess, Version=2015.1.225.1, Culture=neutral, PublicKeyToken=7ce17eeaf1d59342' or one of its dependencies. The system cannot find the file 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.IO.FileNotFoundException: Could not load file or assembly 'Telerik.OpenAccess, Version=2015.1.225.1, Culture=neutral, PublicKeyToken=7ce17eeaf1d59342' or one of its dependencies. The system cannot find the file specified. 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.

I tried to find the reference of Telerik.OpenAccess in all the configuration files to delete it but I don't find it !!!

So I need to know :

  1. How can I fix this problem?
  2. Why I don't have this problem before deploiement?

Orchard won't let me install modules / activate features (like Vandelay Industries, etc.) anymore

I've been running a website using Orchard 1.8.0 for some time now and I remember at some point early in development installing the Vandelay.Meta module to add meta tags/descriptions to my content pages. By pure accident I stumbled upon the fact that the website does not include any meta information on the pages anymore. I logged into the backend to find that the input fields on the content page edit have gone missing. The module was still listed in the module tab, and I tried deactivating and reactivating the feature, but it didn't help.

I logged onto the server and used the console orchard package remove command to delete the vandelay.meta folder in the module folder. The module was now gone from the module tab in the backend (as expected).

I tried reinstalling the module from the gallery, and while it claimed the installation was a success and prompted me to active the feature, it would then not show up in the modules tab, and of course also not on the content page edit site.

I tried to install some other modules like Vandelay.Industries or VXSolutions.Orchard.MetaTags, and I tried installing from the Gallery or from my computer. The result is always the same: The backend first claims that installation was successful, asks me to select the features to activate, and nothing is actually installed.

I checked Orchard's error logs, and here is what I found - but I must admit that this is on a level I have not yet worked on (I usually do frontend stuff, create themes, do some minor razor coding, etc.)

2015-06-25 16:50:16,823 [56] Orchard.Recipes.Services.RecipeHarvester - Default - Could not discover recipes because module 'VXSolutions.Orchard.MetaTags' was not found.
http://ift.tt/1Lxp89M

2015-06-25 16:51:26,024 [34] Orchard.Recipes.Services.RecipeHarvester - Default - Could not discover recipes because module 'VXSolutions.Orchard.MetaTags' was not found.
http://ift.tt/1Lxp89O

2015-06-25 16:51:26,362 [34] Orchard.Recipes.Services.RecipeStepExecutor - Default - Recipe execution 2bf13fda53374162aa942942b24cbbd7 was cancelled because a step failed to execute
http://ift.tt/1Lxp89O
System.InvalidOperationException: Could not enable feature VXSolutions.Orchard.MetaTags because it was not found.
at Orchard.Recipes.RecipeHandlers.FeatureRecipeHandler.ExecuteRecipeStep(RecipeContext recipeContext)
at Orchard.Recipes.Services.RecipeStepExecutor.ExecuteNextStep(String executionId)

2015-06-25 16:51:26,587 [34] Orchard.Exceptions.DefaultExceptionPolicy - Default - An unexpected exception was caught
http://ift.tt/1Lxp89O
Orchard.OrchardCoreException: Recipe execution with id 2bf13fda53374162aa942942b24cbbd7 was cancelled because the "Feature" step failed to execute. The following exception was thrown: Could not enable feature VXSolutions.Orchard.MetaTags because it was not found.. Refer to the error logs for more information.
at Orchard.Recipes.Services.RecipeStepExecutor.ExecuteNextStep(String executionId)
at Orchard.Recipes.Services.R)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)

Can anyone help me find the source of the problem?

Need help in opening .htm file in MVC

I am using MVC4 and Jquery.

I am having issue in opening the .htm file through action method in MVC.

Here is my Code:

   <img src="~/Images/question_frame.png" style="margin-top:3px;height:18px;width:20px;" onclick="window.open('@Url.Action("Help", "Home", new { id = "NMCHelp"})', 'NMCHelp', 'toolbar=no, scrollbars=yes, resizable=yes, top=50, left=50, width=750, height=600');" />

My ActionMethod:

[HttpGet]
        [Authorize]
        public ActionResult Help()
        {
           var result = new FilePathResult("~/help/nmc/enu/Default.htm", "text/html");
                return result;

               }

I am facing issue while trying to open.I am getting error like '$'is undefined.

Please let me know how can I open the .htm file through action method

How to access array values from view in asp.net mvc5?

I need to generate labels in view for each item in an array which is in the model.

This is what I have so far.

Reference.cs

public class Reference
    {
        private string[] itemList = { "Shirt", "T-shirt", "Denim" };


        public string[] Item {
            get{
                return itemList;
            }

            set {
                itemList = value;
            }
        }
        public int ShirtId{get;set;}
        public int TShirtId { get; set; }
        public int DenimId { get; set; }
    }

index.cshtml

@model WebApplication1.Models.Reference

@{
    ViewBag.Title = "Index";
}

<h2>Update Your References Here</h2>
<br>
<p> Please type in the reference code of the item in the corresponding text box</p>
<section id="reference-update">
   @using (Html.BeginForm()) { 
        <fieldset>
            <legend> Reference Items</legend>

            <div class="form-horizontal">


                <div class="item">
                    @Html.LabelFor(model=>model.Item[0])
                </div>
                <div class="input-lg">
                    @Html.TextBoxFor(model => model.ShirtId)
                </div>
            </div>
        </fieldset>
   }
</section>

But I do not get a label named "Shirt" in the view(A label Named "Item[0]" appears). How do I fix this? Note that I am a beginner.

How to pass Parameter to a partial view: Object reference not set to an instance of an object

I have a partial view that renders one control on the page, this control is for certain fields that are long. This is how I defined it:

@model long
@(Html.Kendo().MultiSelectFor(x => Model)

I'm trying to render this partial view in other views with something like:

@Html.Partial("MultiSelect/partialView", @Model.longField)

This give me an Object reference not set to an instance of an object exception.

Please guide me about the right syntax to achieve this.

dimanche 28 juin 2015

How to enable use of both named and unnamed url parameters in Asp.Net MVC

Most likely a very basic question, but still: In an ASP.Net MVC application, how can I enable a controller to respond to URLs that have either named or unnamed URL parameters.

With the following controller:

[Route("test/display/{scaleid}")]
public ActionResult Display(int scaleid)
{
    return View();
}

I try two URL requests - the first one works, the second one (where I specify the parameter name), doesn't work. Why is this?

http://localhost:43524/Test/Display/11
http://localhost:43524/Test/Display/?scaleid=11

Store JWT token in cookie

This is my setup:

  • 1 authentication server which gives out JWT token on successfull authentication.
  • Multiple API resource servers which gives information (when the user is authenticated).

Now I want to build my ASP.NET MVC frontend. Is it ok to take the token, which I receive after authentication, and put it in a cookie so I can access it with every secured call I need to make? I use the RestSharp DLL for doing my http calls. If it has a security flaw, then where should I store my token?

I would use this code for the cookie:

            System.Web.HttpContext.Current.Response.Cookies.Add(new System.Web.HttpCookie("Token")
        {
            Value = token.access_token,
            HttpOnly = true
        });

session cleared on second ajax call

Here my problem is little weird, I encounter it only on my production server. Basically I loose session values on second ajax call. Whole process is like user clicks a button to initiate sync process, which involves two ajax hits, first a post request and on successful completion of this a second get request.

My code is like below:

jQuery Code:

//User clicks "SyncButton" to initiate sync process
    $('#SyncButton').on('click', function (event) {
        //Some UI Code
        $.ajax({
            type: 'POST',
            beforeSend: startService,   //startService has some UI code
            url: "FirstAjaxURL",
            data: null,
            contentType: "application/json",
            success: function (data) {
                ServiceSuccess(data);
            },
            error: serviceError
        });
    });

function ServiceSuccess(data) {
    var html = ''; //code to get html from data
    $('#divSync').html(html);
    if (!($('#delete').length > 0)) {
        RenderBusinessGrid();
    }
};

function RenderBusinessGrid() {
    var allBusiness = "";
    $.getJSON("SecondAjaxURL", function (data) {
        //Some UI handling code
    });
    $('#divSyncDetails').height('400px');
}

MVC code:

[HttpPost]
public string FirstAjaxURL()
{
    //make some DB hits
    //fetch data
    //create couple of zip files
    //save them in two separate folders in separate folders under root directory

    /*LOGS SUGGEST ALL SESSION KEYS WERE AVAILABLE HERE*/
    return "some string result";
}

public ActionResult SecondAjaxURL()
{
    /*LOGS SUGGEST SESSION KEYS NOT AVAILABLE HERE*/

    //do some DB operation 
    return jsonResult;
}

What all I have tried so far:

  1. Checked IIS settings for application pool recycle time, they seem to be fine
  2. Session timeout is set to large value, it doesn't timesout if I leave system for idle
  3. Confirmed there's no unhandled exception in first ajax hit
  4. Tried saving zip files outside application's directory structure
  5. Tried replacing $.getJson with $.ajax(I know its stupid to try this but you never know... :)

Note: In majority of cases session timesout on second ajax call the very first time user initiates the sync process. While we observed quite some cases where this happens second or third time.

Please suggest what else I could try/verify to get root-cause of this issue, its bugging me big time. All pointers are welcome.

Thanks, Ravi

ASP.NET MVC regular expression for comma separated strings

I need to do MVC unobtrusive client side validation using regular expression in my ASP.NET MVC 5 project.

Valid Input is comma separated string values, for example: string1, string2, string 3 etc.

I tried below regEx pattern for comma separated strings but it's not working as expected. Could anyone tell me what's wrong in below expression ?

[RegularExpression(@"/^[a-zA-Z]{1,20},[a-zA-Z]{1,20}$/",
                        ErrorMessage = "Please enter comma separated list")]
    public string SettingOptions { get; set; }

Thanks in Advance.

Bring back values in Jquery-tokeninput in editable mode

I am using jquery-tokeninput plugin in application and it is working fine for searching data from database. When submit the data it submitted successfully.

My tables allow dynamically add rows as below.

hidden table for dynamically adding rows

 <table id="Newdiagnosis" style="display:none">
    <tr>
    <td><input id="diag-%" class="diag" style="width:200px" type="text" name="provider_diagnosis_dtls[#].diagnosis_code" value /></td>
    <td><input id="desc-%"  class="diag_desc" style="width:500px" type="text" name="provider_diagnosis_dtls[#].diagnosis_desc" value /></td>
    <td>
    <input id ="level-%" type="text"name="provider_diagnosis_dtls[#].diagnosis_level" readonly value />
    <input type="hidden" name="provider_diagnosis_dtls.Index" value="%" />
    </td>
    </tr>
     </table>

actual table

<table id="diagnosis" >
<tr>
<th style="width:200px">
Diagnosis Code
</th>
<th style="width:500px">
Diagnosis Description
</th>
<th>
Diagnosis Type
</th>
<th style="width:6px">
</th>
</tr>
@if (Model != null)
{
 for (int i = 0; i < Model.provider_diagnosis_dtls.Count; i++)
 {
<tr>
<td>@Html.TextBoxFor(m => m.provider_diagnosis_dtls[i].diagnosis_code)</td>
<td>@Html.TextBoxFor(m => m.provider_diagnosis_dtls[i].diagnosis_desc)</td>
 <td>
 @Html.TextBoxFor(m => m.provider_diagnosis_dtls[i].diagnosis_level,new { @readonly = "readonly" })
<input type="hidden" name="provider_diagnosis_dtls.Index" value="@i" />
</td>
</tr>
}
}

Jquery add rows dynamically

$("#N").click(function () {
var index = (new Date()).getTime();
var clone = $('#Newdiagnosis').clone();
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
clone.html($(clone).html().replace(/"token-input-diag-%"/g, 'token-input-diag-' + index));
clone.html($(clone).html().replace(/"token-input-desc-%"/g, 'token-input-desc-' + index));
clone.html($(clone).html().replace(/"diag-%"/g, 'diag-' + index));
clone.html($(clone).html().replace(/"desc-%"/g, 'desc-' + index));
clone.html($(clone).html().replace(/"level-%"/g, 'level-' + index));
var html = clone.html();
$("#diagnosis").append(clone.html());
  $("#diagnosis").find(".diag").last().tokenInput("@Url.Action("SearchDiagnosis","Preapproval")",
 {
   theme: 'facebook',
   preventDuplicates: true,
   searchingText: 'Searching diagnosis code...',
   tokenLimit: 1,
   hintText: 'Diagnosis Code'
  });

  $("#diagnosis").find(".diag_desc").last().tokenInput("@Url.Action("SearchDiagnosis_desc","Preapproval")",
 {
   theme: 'facebook',
   preventDuplicates: true,
   searchingText: 'Searching diagnosis desc...',
   tokenLimit: 1,
   hintText: 'Diagnosis Description'
   });
});

Now when the user open the request form for the first time there will be no row in the diagnosis table. When the user click on button with id N the new row will get added and jquery-tokeninput is added to it successfully. Also able to search the database. Then user submitted the request.

Now the user opened the same request for modification. Now the earlier added rows will come up with data stored in database but here the issue facing is those are coming as text box because I use @Html.TextBoxFor no jquery-tokeninput is there but if user click on the button N the newly added row will have the plugin. How can i attach the plugin to the already available rows also. I'm stucked here.

How to enable https on IIS 8.0?

I am using IIS 8.0.9200. In my local computer - I want to set up the https enable sites means site which I currently run must be run over https(SSL). For that when I seen in BINDINGS of website – where type drop down which shows http/https settings, in my computer it is always seen as disabled on add/edit mode. I am using windows 8.1 version.

so how to make enable that dropdown to make https? and what are the next steps then to achieve that?

What is the performance difference between rendering View vs rendering an HTML file in ASP.NET MVC?

Considering both containing same static content, what is the difference between rendering a view VS a HTML file from an action in ASP.NET MVC?

Background: I have some static content such as about page which I'm rendering as ActionResult view. I can also keep them in some HTML files.

Question: Does it make any sense to port the static content from view files to HTML files? I believe it will save server from processing View engine tasks - which is the reason for port (correct me, if I'm wrong).

One more important question: How do I handle Viewbag.Title thing? This is passed to _Layout from view file only?

Optimise loading large dataset to a table in asp.net mvc 4

I'm creating asp.net mvc 4 application, In that application I'm loading many rows to a table.

However this function working smoothly for small and average data sets which means if number of rows less to 1000 or less to 5000 this is loading with average time

This view of that table

enter image description here

But when the number of rows going high which means more than 5000 this take too much time to load those all rows into table

Here the LINQ query that is use to load values to table

public ActionResult StudentIndex()
{
    return View(db.tbl_HEI_student.Where(x => x.Create_By == userid).OrderByDescending(s => s.Create_Date).ToList());

}

Here once it load values to table , using Jquery Table sorter function it is doing pagination function , I ignored sorting.

This is jquery script code snippet

<script type="text/javascript">
    $(function () {
        $("#table-hover")
            .tablesorter({
                widthFixed: true
            })
            .tablesorterPager({
                container: $("#pager"),
                size: $(".pagesize option:selected").val()
            });
    });

 </script>

How can I speed up loading for large data-set ? what are the method should I follow?

jquery validationg .jpg extension pass for any file extension

I am validating a picture uploaded is jpg or not as below code

alert(fileName);

if (fileName != '') {
alert("Entered if");
var ext = $('#pic').val().split('.').pop().toLowerCase();
if (ext != 'jpg')
{
 error = 1;
alert(error);
}
}

If i select any file this validation is passing. So I put two alerts. Now the first alert will show the file path selected. but any how it is not getting inside the if condition so second alert is not doing so no check for the extension is happening. The if condition is true because fileName show the file path so it is not equal to ''

Giving Role to LDAP Authorization in ASP.NET MVC

I am using ASP.NET MVC and LDAP as authentication. It was successful. but I don't have any idea about how to give roles to the users. for example, I can login via LDAP with username "xxxx", and I want to give that "xxxx" role as "admin". then I can control the view with [Authorize(Roles="admin")]. How can I do that?

View Could Not Be Found

In a ASP.NET MVC website; does every view need to have a corresponding/associated Model and Controller?

I am building the bare bones of my website; so I have created all the views but not the Models or Controllers yet. I want to be able to view a page (that contains no content associated with a model or any functionality that a controller should handle - yet). So at this point every view (cshtml page) is a static HTML page.

But when I go to access any view/page I get the error:

The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /TeamMember/raiseIssue

raiseIssue.cshtml content:

@{
    Layout = "layouts/main.cshtml";
}
<form action="@ViewBag.PostUrl" method="post">
    <div class="row feedback-input text-center">

         <textarea name="Text"></textarea>  
    </div>
    <div class="row text-center">
         <button type="submit" class="btn btn-default btn-standard">Submit</button>
    </div>
</form>

how to render text inside by using Html.raw in mvc view

I am trying to display html text from database and show it in view. Example: In my database:

<p>
    <strong>Stackoverflow</strong></p>
<p>

In View: Stackoverflow

and I use @Html.raw(myproperty) But the problem is The text it's not render inside div.

Here is my code in index page:

 <p style="word-wrap: break-word;overflow:hidden;white-space: nowrap;text-overflow:ellipsis">
    @Html.Raw(item.Body)
</p>

Here is my screenshot about the problem: enter image description here

Please help me. Many thanks.

regex pattern.test() works in chrome but not in IE8

I am checking regular expression in jquery part of my razor as below

function isValidarabicname(arabicname) {
    var pattern = new RegExp(/^[\u0600-\u06ff ]+$/);
    return pattern.test(arabicname);
};

$("#delBtn").on('click', function() {
    if (!isValidarabicname(arabicname)) {
        $("#errorDiv").show(500).html("Enter only arabic letters");
        $("#arabic_name").focus();
        error = 1;
    }
});

this validation is working fine in Chrome but it get failed in IE 8. Do i need to change anything to make it work in IE 8?

Update Claims after user login

Is it possible to update claims after user login? I have frontend and admin panel in my site, basically I'm using claims to achieve this. If a user is logged in as Susan in frontend, I did something like this in my code :

var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

userIdentity.AddClaim(new Claim("Id", this.UserName));
... //other claims here

So when user finally login on admin panel (when still logged on in frontend), I just want to add more claims for example :

userIdentity.AddClaim(new Claim("BackEndId", this.UserName));

How to achieve this?

dd-mm-yyyy format for datepicker of MVC is not working in Chrome

In my MVC5 Razor code for entering Date of Birth I am using a datepicker as below

    @Html.EditorFor(model => model.date_of_birth, 
new { htmlAttributes = new { @class = "m-wrap  datepicker" } })

Here for the model.date_of_birth an EditorFor is calling and making it as a datepicker with @class = datepicker

Then the datepicker is initiated at the script area with below code

 $('.datepicker').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true
        })

Here the date format is 'yyyy-mm-dd' and it is working fine, but the user want it to be in dd-mm-yyyy format. So I changed the format in script as dd-mm-yyyy In Internet Explorer it is working fine but in Chrome it is giving an error for some date

eg:  14-05-2015

The field Date of Birth* must be a date.

the date 11-05-2015 is working fine in chrome also. So I guess Chrome is taking the date format in mm-dd-yyyy.

The format 'dd-M-yyyy' is also working correctly only error coming for dd-mm-yyyy

Any way to overcome this browser specific error?

Edit

$.validator.addMethod('date', function (value, element) {
    if (this.optional(element)) {
        return true;
    }
    var valid = true;
    try {
        $.datepicker.parseDate('dd/mm/yyyy', value);
    }
    catch (err) {
        valid = false;
    }
    return valid;
});

$(function () {

 $('.datepicker').datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true
        })
});

How can I extend MvcForm so that It will not generate a form tag?

I would like to add a condition to a html beginform. If the condition is false, I dont want the form tag to be generated.

Similar to this code:



        public static MvcHtmlString If(this MvcHtmlString value, bool evaluation)
        {
            return evaluation ? value : MvcHtmlString.Empty;
        }

Expand User.Identity properties

I have a site with frontend and admin panel. Both have login page and user should be able to login on both frontent and admin panel with different user. By default User.Identity.IsAuthenticated is used to check if user is currently logged in, I want something like User.Identity.IsAdminPanelAuthenticated. So if a user only logged in on admin panel but not on frontend then IsAuthenticated will return false but IsAdminPanelAuthenticated will return true.

.Submit() in jquery not firing

i am having a razor code as below

        @using (Html.BeginForm("OtherUpdateRequest", "Members", FormMethod.Post,
 new { name = "form1", id = "form1", enctype = "multipart/form-data" }))
     {
    .......
<input type="button" value="Update Members" name="update" id="update" class="btn btn-success">

    }

and in script area after some validation the form is getting submitted as below

 $("#update").on('click', function () {
......
            if (error == 0)
            {
                alert(error);
                $("#errorDiv").hide();
                $("#form1").submit();
            }
});

it is alerting the value of error. SO it is getting inside the if condition but the form is not getting submitted.

If i change the input code as below it will get submitted but i need some jquery validation so the submit can only done through jquery. Please let me know anything wrong I am doing.

    <input type="Submit" value="Update Members" name="update" id="update" 
class="btn btn-success">

HTTP 400 Error ASP.Net MVC

I'm developing an MVC application and on some pages we are acepting data sent through by ajax. Recently I'm getting lots of 400 Error message and I was wondering if there is any way to capture the data sent to sever which caused the 400 error using action filters or similar mechanisms. For me there is no way to figure out what's the problem without actually getting the data which caused the error. Looking forward to you ideas. Thanks.

EWS - Appointment.Subject returns Organizer and not the Subject entered and displayed in Outlook

I am writing a ASP.NET MVC 5 application, .NET 4.5. The page is displaying Appointments from an Exchange Server. That works nicely so far.

The problem: I just created a new meeting in Outlook 2013. Subject: Roomplan Showcase, I am "John Doe" (Organizer) and added Richard Miles to the meeting. The next time the page refreshes, the page displays: Title: John Doe; Attendants: John Doe, Richard Miles

What it should display: Title: Roomplan Showcase; Attendants: John Doe, Richard Miles

I debugged through the creation of this item and realized that indeed the Subject-Member of the appointment contains the Organizer string. The real subject is nowhere. I then checked in Outlook if I messed up the creation of the meeting, but in Outlook, OWA or other Calendars the Subject is correctly displayed. On top of this confusing behavior any other meeting (on different rooms, created prior to this test meeting) displays the correct Subject. So if I create meetings for my testroom, the subject gets messed up, but the real rooms, where real people create real meetings, the subject is pulled correctly from EWS.

Is there some configuration I can do on the Exchange? What is causing this problem?

ASP.NET Identity - Anonymous profiles

I want to use anonymous profiles to store and use profile data without authenticated. How to enable anonymous profiles is described on page http://ift.tt/1HqkMBu

Profiles can also work with anonymous users. Support for anonymous profiles is not enabled by default, so you must explicitly enable it. In addition, when you define profile properties in the Web.config file, you must explicitly make them available individually for anonymous users. Profile properties do not support anonymous access by default because profiles may be designed to work with authenticated users, and many properties are likely to pertain to personal information that is not available for anonymous users.

But I'm not sure, that I can use profile data for anonymous users. It says, that by default I can't use profile data. But not by default, have I ability to use profile data for anonymous users and if "yes" then what should I do? I confused...

Raven paging queries in a specific way

I'm developing an ASP.NET MVC application using RavenDB 3. I don't have a lot of experience with raven.

In general, when executing queries to display data, the first 128 items are returned on the page. More records are added in an "infinite scroll"-manner by using paged queries.

Now, however, I have the requirement that items are loaded in 'groups'.

Assume the following class:

public class Item {
  public string Id { get; set; }
  public int Group { get; set; }
  public string text { get; set; }
}

Assume the database contains 40 items having group='1', 40 items having group='2' and 50 items having group='3'.

This is a total of 130 items. This would mean that the last 'group' fetched would not be complete. It would be missing 2 items.

I would like a mechanism that is aware of this, so that it would fetch at least 128 AND would fetch 'extra' if the last group is not completely included.

Afterwards, when I fetch the next page, I would like it to start with the next group.

Is there any way I can make this work without 'fabricating' a single page myself by doing more than one call?

EDIT: I cannot assume the groups are perfectly equal in size, but I can assume the sizes will be 'simular'

Also, I cannot change the design to store all items in a single 'group'-object for instance.

Update SHA-1 to SHA-2 MVC C# SSH

I was following instruction from here to set up SSH

http://ift.tt/1AXc9f4

At the step 5 when I run my app I see crossed out https, I read it's because I use SHA-1.

How to upgrade it ?

asp.net attribute routing No HTTP resource was found that matches the request URI

I am using asp.net mvc5 attribute routing as follows

[RouteArea("api")]
[RoutePrefix("data")]    
[Route("{action}")]
public class APIMasterDataController : Controller  

to achieve http://localhost/myapp/api/data/ ,

[RouteArea("api")]
[RoutePrefix("authentication")]
[Route("{action}")]
public class APIAuthenticationController : Controller

to achieve http://localhost/myapp/api/authentication/

and

[RouteArea("api")]
[RoutePrefix("transaction")]
[Route("{action}")]
public class APITransactionController : Controller

to achieve http://localhost/myapp/api/transaction/

But i am getting below error while accessing the url :

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/myapp/api/data/masters'.","MessageDetail":"No type was found that matches the controller named 'data'."}

I have added

routes.MapMvcAttributeRoutes();

in my RouteConfig file,

I have also updates Application_Start() with :

AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

but I am still getting above mentioned error. What am I doing wrong / missing ?

How to authenticate user in Web API 2 when being part of a legacy ASP.NET MVC application?

I have a Web API which is currently used by AngularJS apps in an ASP.NET MVC web application. The MVC application is utilizing ASP.NET Forms Authentication as authentication mechanism. How should I authenticate a user of the Web API when the client is not the web client but e.g. a stand-alone service. What I've done right now is adding a login method to the Web API which gives anyone with right credentials access:

[Route("api/v2/login"), HttpPost]
[AllowAnonymous]
public IHttpActionResult Post([FromBody]Credentials credentials)
{
    var principal = FindPrincipal(credentials);
    if (principal != null)
    {
        FormsAuthentication.SetAuthCookie(principal.Identity.Name, false);
        return Ok();
    }
    return Unauthorized();
}

My question is if this is how this should be solved or if there's a better way?

How to see what ajax request is actually being submitted

I'm making ajax requests to controllers in ASP MVC 5 from JQuery. The requests are failing. However, if I put in the request by hand, for example /Sale/fillVarietiesSelect?speciesId=2, I get the correct response. I must be doing something wrong with my ajax request, but I can't see it. It would help me debug if I could see the actual request being made, but it doesn't show up in the URL bar (it is a GET request). Is there a way I can intercept or view the actual request?

Multiple list items to one model

I have now been stumped the last few hours trying to get this to work and have only been partially successful. I'm trying to create an order form where when you select a Panini you can have multiple toppings that are in the database from the Topping class, at the moment I can only get it to show a drop down and select 1 topping. Then I need to be able to have multiple paninis go into the Order class including the toppings for each panini. I have 3 classes:

Topping:

[Key]
public int ToppingId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public virtual ICollection<Panini> Panini { get; set; }

Panini

[Key]
public int PaniniId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int ToppingId { get; set; }
public virtual Topping Topping { get; set; }
public virtual ICollection<Order> Order { get; set;

Order

[Key]
public int OrderId { get; set; }
public decimal TotalCost { get; set; }
public int PaniniId { get; set; }
public virtual Panini Panini { get; set; }

As I mentioned I can get the Pannini page to have a dropdown of the Toppings but I can only select one, but I need to be able to select a multiple of them. Same for the Order, I can get a dropdown of the available Paninis but can only select one.

Am I doing this the right way. If not can anybody point me in the right direction.

Many thanks.

Why is the ViewModel data null on POST ASP MVC

I'm doing forms on ASP .NET MVC 5. I thought it was simple enough to just post with a matching model in the action but I keep getting null values on my action. For example,

@model Tuple<ManageLoginsViewModel, IndexViewModel, LocalPasswordModel, SetPasswordViewModel>

<p>
    You do not have a local password for this site. Add a local
    password so you can log in without an external login.
</p>

@using (Html.BeginForm("SetPassword", "Manage", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Set Password</legend>
        <div>
            <div class="LabelPassword">
                <label>New password</label>
                <input data-val="true" data-val-length="The New password must be at least 6 characters long." 
                    data-val-length-max="30" data-val-length-min="6" 
                    data-val-required="The New password field is required." 
                    id="NewPassword" type="password">
            </div>
            <div class="LabelPassword">
                <label>Confirm Password</label>
                <input data-val="true" data-val-length="The New password must be at least 6 characters long." 
                    data-val-length-max="30" data-val-length-min="6" 
                    data-val-required="The New password field is required." 
                    id="ConfirmPassword" type="password">
            </div>
        </div>
        <input type="submit" value="Set password" />
    </fieldset>
}

While numerous post suggest on renaming the action parameter to something that doesn't match the properties on my view model, I have not found a solution to this.

enter image description here

weirdly enough, there is no post data that Chrome shows. Is this an error in my html or my handling of the post?

and finally, here's the action method:

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> SetPassword(SetPasswordViewModel setPassword)
        {
            if (ModelState.IsValid)
            {
                var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), setPassword.NewPassword);
                if (result.Succeeded)
                {
                    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
                    if (user != null)
                    {
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    }
                    return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(setPassword);
        }

I'm sure its something simple, but I've got no indication where things are going wrong now, other then the blanks on POST that is shown in Chrome (well, the anti-forgery token is displayed at least). Is this the problem?

What is the proper scoping for a Quartz.net Scheduler instance in ASP.NET applications?

I'm running Quartz.net in-process with my ASP.NET MVC application.

To start the scheduler you of course have to do something like this:

    ISchedulerFactory schedulerFactory;
    IScheduler scheduler;
    schedulerFactory = new StdSchedulerFactory(properties);
    scheduler = schedulerFactory.GetScheduler();
    scheduler.Start();

Assuming that I want only a single instance of the scheduler in my application (is this a good assumption?), is it a best practice to simply define scheduler as static so that I have access to the scheduler throughout the application?

Video does not resume after pausing

I am using VideoJS to host a video in my MVC application. It is working except for one small issue. When I pause the video in Google Chrome, then resume it, the video breaks with the following error message:

A Network Error caused the video download to fail part-way.

Here is my relevant html code:

<div class="row">
    <div class="col-lg-6 text-left">
        <p>
            <ul>
                <li><a href="javascript: void(0);" id="video1">Video 1</a></li>
                <li><a href="javascript: void(0);" id="video2">Video 2</a></li>
                <li><a href="javascript: void(0);" id="video3">Video 3</a></li>
            </ul>
        </p>
    </div>
    <div class="col-lg-6">
        <video id="videoPlayer" class="video-js vjs-default-skin" controls preload="auto" width="640" height="264">

        </video>
    </div>
</div>

And here is my javascript code:

<script type="text/javascript">
    $(function() {
        videojs("videoPlayer", {
            "controls": true,
            "loop": "false"
        }, function () {
            // 
        });

        $('#video1').click(function() {
            var myPlayer = videojs('videoPlayer');
            myPlayer.src({ type: "video/mp4", src: "/Videos/Video1.mp4" });
            myPlayer.play();
        });

        $('#video2').click(function () {
            var myPlayer = videojs('videoPlayer');
            myPlayer.src({ type: "video/mp4", src: "/Videos/Video2.mp4" });
            myPlayer.play();
        });

        $('#video3').click(function () {
            var myPlayer = videojs('videoPlayer');
            myPlayer.src({ type: "video/mp4", src: "/Videos/Video3.mp4" });
            myPlayer.play();
        });
    });
</script>

I tested this with other browsers. The issue only seems to occur using Google Chrome. It works fine in Internet Explorer and FireFox.

Ajax pass values from view to controller

so I'm trying to pass some values from my view to the controller, the controller gets a list and returns it.

when I try to get the values from my textboxes etc. they are all undefined... not sure what exactly I'm doing wrong here. pretty new to javascript..

here's the js code

<script type="text/javascript">
$(document).ready(function () {
    $("#getFreeApartements").on('click', function () {

        var amounta = $('#amounta').val();
        var amountc = $('#amountc').val();
        var amountan = $('#animals').val();
        var arr = $('#arrival').val();
        var dep = $('#departure').val();
        var atype = $('#atype').val();


        $.ajax({
            type: 'GET',
            data: { 'amountp': amounta, 'amountc': amountc, 'amountanimals': amountan, 'arrival': arr, 'departure': dep, 'apartmentType': atype },
            url: '@Url.Action("GetFreeApartements", "Bookings")',
            success: function (result) {
                $('freeAp').html(result);
            }
        });
        alert(amounta); // --> return undefined

    });
});

textboxinput field

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

controller:

        public ActionResult GetFreeApartements(int ap, int ac, int aa, DateTime arr, DateTime dep, ApartmentType type)
    {
 //do some stuff with received values here...
        var freeApartements = db.Apartments.ToList();
        return Json(freeApartements, JsonRequestBehavior.AllowGet);

    }

I also tried serializeArray without any success... I'm not getting any errors in the explorer console.. the function gets called, but values are null.. --> undefined should be the error.

any ideas?

How to detect "leave a page" exactly if user opens other page in new tab? [duplicate]

This question already has an answer here:

I wanna exploit a special case when user leaves a page. I create a method to do something when user leaves a page. But, if user is staying on this page, and clicks a link to open new page in new tab. So, does user leave page?

Can you tell me a hint? Thank you!

p/s: I'm using MVC 5 and I can use jQuery/javascript.

How to write a file path in manifest when the file is located in a different project of the ASP.Net MVC solution?

CACHE MANIFEST
# version 1

CACHE:
Content/bootstrap.css
Content/bootstrap-theme.css
Content/bootstrap-datetimepicker.css
Content/style.css
Scripts/modernizr-2.8.3.js
Scripts/jquery-2.1.4.min.js
Scripts/moment.js
Scripts/bootstrap.js
Scripts/bootstrap-datetimepicker.js
Scripts/PrintVizScripts/spa.js
**Model/Models/print_job.cs**
**Model/Models/report_category.cs**
**Model/Models/report_type.cs**
**ViewModel/FilterViewModel.cs**
**Controllers/SPAController.cs**
**Controllers/DataTableController.cs**
**Controllers/ReportCategoryTypeController.cs**
**Views/Shared/_Layout.cshtml**
**Views/SPA/Index.cshtml**
**Views/ReportCategoryType/Index.cshtml**

The first files are well added to the cache but not the ones in bold, here is the error I get:

error

These files are located in another project in the solution and Model is the name of the other project:

**Model/Models/print_job.cs**
**Model/Models/report_category.cs**
**Model/Models/report_type.cs**

Prevent to use default model data annotations in ViewModel

I started working on my first serious MVC project for school unfortunately without defining the data annotations to the model first (so did not set "required" annotation, limit to size of attribute names etc.). I work with a viewmodel, and after adding the annotations the model is causing my ViewModel state to get invalid when posting the form.

It seems like it's the email required that is causing the issue. It is not used on viewmodel and in the form and it seems the viewmodel expects it will get it. Is there a way the form to stop demanding this field by setting some limitation in viewmodel (or controller). I would really prefer not to change the structure of the application (if I start from the scratch I would probably do this a bit different, but not much time is left to finalize the project)

Customer (Model)

public Class Customer(){
    public int Id { get; set; }

    [Required(ErrorMessage = "Required")]
    [StringLength(25, ErrorMessage = "Message"]
    public string Name { get; set; }

    public string Logo { get; set; }

    //[Required(ErrorMessage = "Email required")]
    //[Display(Name = "E-mail")]
    //[RegularExpression(xxxx, ErrorMessage = "not correct")]
    public string Email { get; set; }

    public int UserId { get; set; }
}

ViewModel

public class CustomerEditViewModel
        {
        public Customer Customer { get; set; }

        [FileTypes("jpg,jpeg,png")]
        [FileSize(1024 * 1024, ErrorMessage = "Max x bytes")]
        public HttpPostedFileBase File { get; set; }
        }

adding objects with foreign keys without having to provide the foreign key

I have an asp.net-mvc project with the following set up:

class Person {
 int PersonId {get; set;}
 List<Activity> Activities {get; set;}
} 
class Activity {
 int ActivityId {get; set;}
 int PersonId {get; set;}
 [ForeignKey("PersonId")]
 Person Person {get; set;}
}

now, when I add a new activity for a person, I send an ajax POST and the action method does the following:

public ActionResult AddActivity(int Id) {
 var activity = new Activity();
 activity.PersonId = Id;
 db.Activity.Add(activity);
 db.SaveChanges();  
}

is this a bad way of adding an activity because I'm manually adding the foregin key?

is there a way to do this without having to provide the PersonId foreign key and let it be generated automatically (maybe getting the person object, updating its list of activities and then marking it as EntityState.Modified)?

TeamCity + ASP.NET Webapp: Error about unclosed string literal?

I have a solution where all projects are targeting .NET v4.5.1.

TeamCity (v9.0.4) previously has built the solution just fine.

Added an Asp.Net web application (MVC + WebAPI) to the solution, still targeted at .NET 4.5.1.

It Works on My Machinetm, but TeamCity now fails the build with the following MSBuild error:

[src\app\Web\Web.csproj] C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets(186, 67): error MSB4025: The project file could not be loaded. There is an unclosed literal string. Line 186, position 67.

Those might be the line numbers in the targets file that threw the error, because in my file all I see is a </ProjectReference> (which corresponds correctly to two project references that are there.

Any idea what could be causing this?

Simple Login with ASP.Net MVC5

I have been trying to get my head around OWIN and Identity to get it play well with my Existing app. The application was coded in Plain ASP.Net and I want to port it to MVC to organize it better. The app have established database including Users table so using Identity table is not option. The wall I hit with Identity is that it requires Email and my system is NOT supposed to demand user email. After trying almost everything (days reading almost every answer on the subject) I have come to conclusion that it will take more time to get it done, and that brings me to my question.

Being PHP guy (jumped to ASP.Net not long ago) I could easily make a working login in 10minutes and now I need a thing like it, something like

$user = User::findByUserName($username); //somehow here I find user from database
if($user!=null)
{
    $_SESSION['isLoggedIn'] = true;
    $_SESSION['fullname'] = $user->fullName;
}
else
{
    //redirect to login with error
}

I cannot find a session class in MVC5. Is that even possible? If no, is there a simple route to solve my issue?

Read server response in bootstrap file input plugin in ASP.NET MVC site

I have an ASP.NET MVC app. This app uses the bootstrap file input plugin. After a file is uploaded, I need to examine the JSON that is returned. At this time, my code is structured like the following:

Index.cshtml

<input id="myPictures" name="files" type="file" multiple>

...

$('#myPictures').on('filebatchuploadcomplete', function(event, files, extra)   
{
  console.log(event);
  console.log(files);
  console.log(extra);
});

$("#myPictures").fileinput({
  maxFileCount: 1,
  overwriteInitial: false,
  uploadUrl: "/Pictures/Upload",
  uploadAsync: true,
  previewSettings: {
    image: {width: "200px", height: "200px"}
  }
});

PicturesController.cs

public class PicturesController
{
  [HttpPost]
  public ActionResult Upload(FormCollection form)
  {
    // Do stuff
    var resultId = GetResultId();
    return Json(new { id = pictureId }, JsonRequestBehavior.AllowGet);
  }
}

My problem is, while the JSON is being returned, I cannot seem to access it in the filebatchuploadcomplete event handler. I have confirmed that the Upload action is returning the JSON I expect by using breakpoints and Fiddler. However, I cannot figure out how to read the response to react based on the server's result.

Can somebody please help me figure out how to read the value of the id property in the JSON object that is returned from the server? It's driving me nuts!

Thank you

Implementing OpenID in ASP5

I'm attempting to implement Steam OpenID integration into an ASP5/MVC6 site. The existing OpenID libraries do not work with ASP5 as they seem to rely on HttpContext, which doesn't exist.

This is the only compatible library that I can find:

 "Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-beta4",

I've configured it in Startup.ConfigureServices like so:

    public void ConfigureServices(IServiceCollection services)
    {
        ..
        services.ConfigureOpenIdConnectAuthentication(options =>
        {
            options.Authority = "http://ift.tt/1glcWoz";
            options.ClientId = "[ClientIDHere]";
        });
    }

and in Startup.Configure:

app.UseOpenIdConnectAuthentication();

My real question is a simple one, how do I actually use this library in my application to create the OpenID requests? Documentation seems non-existent on this library (typical for a beta, of course) and examples are scarce.

Convert JavaScript Map to a C# Dictionary

I am using MVC to create a web page. I my View, I use JavaScript to generate a list of IDs and whether that are valid. For each pair, I end up with two JS varables such as:

var id = 123;
var isValid = true;

I am currently storing that data in a JS Map and just do:

var myJSMap = new Map();
myJSMap.set(id, isValid);

to insert the sets of data.

I then want to send this data to my C# Controller Action. My Controller Action method, however, is expecting a Dictionary Object:

public virtual ActionResult MyAction(Dictionary<int, bool> dictionary){
   return View();
}

Since C# is a server-side and JS is a client-side language, I am having problems sending data from one to the other. I tried different options to somehow send my JS map data from my View to my Controller, but so far have not been able to get any of them to work. Are any of my options below doable, or is there another way to send a group of pairs of JS data to a C# Controller Action method?

Option 1:

Store my JS variables in a JS Map like I currently am doing. Then, is there a way to convert my JS Map to a C# Dictionary (either copy all the values or somehow do it while sending it to my Controller like with ajax)?

Option 2:

Create a Dictionary<int, bool> in my View right away. Then, instead of inserting my two JS variables into a JS Map, can I somehow insert my two JS variables into a C# Dictionary? I would basically want to do @myCSDictionary.Add(id, isValid); using Razor syntax, yet can't since id and isValid are JavaScript variables.

Option 3:

Instead of using a JS Map and a C# Dictionary, is there a different data type (that can store pairs of a data) I can use that matches up in both languages so that I would be able to just send the JS Object to my Controller using Ajax like you can do for int and string?