FAQ Database Discussion Community


How to get started with Visual studio 2012

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,visual-studio-2012
I want to create web application using Visual Studio 2012. The application should login into a website and report numerical findings on the UI. The language used will be Visual C#. I have loaded the application and selected on the menu: File> New > Projects. A window appears with multiple...

Passing complex array from Controller to View ASP.NET MVC

c#,asp.net,asp.net-mvc,asp.net-web-api
I have a model in my ASP.NET MVC application: public class SearchArrayModel { public long ID { get; set; } public string Name { get; set; } public struct AttribStruct { public string AttribName { get; set; } public string[] AttribValues { get; set; } } public AttribStruct[] AttribStructTable {...

AngularJS Error: [ng:areq] Argument 'MyController' is not a function, got undefined

html,asp.net-mvc,angularjs
I'm getting error with angular JS Error: [ng:areq] Argument 'MyController' is not a function, got undefined, when trying to use bundles. However when I explicity include the app in my html using script tags it works. Bundle Config.cs bundles.Add(new ScriptBundle("~/bundles/myweb") .IncludeDirectory("~/Scripts/myweb", "*.js") .IncludeDirectory("~/Scripts/myweb/Controllers", "*.js") .Include("~/Scripts/myweb/Controllers/myController.js") .Include("~/Scripts/myweb/myweb.js")); With this HTML does...

How to map between two entities before paging

c#,asp.net-mvc,entity-framework
Consider the code below: public ActionResult Index(int? page) { List<ProviderViewModel> viewModel = new List<ProviderViewModel>(); List<Provider> businessModel = db.Providers .OrderBy(t => t.Name); foreach (Provider provider in businessModel) { viewModel.Add(new ProviderViewModel(provider)); } int pageSize = 9; int pageNumber = (page ?? 1); return View(viewModel.ToPagedList(pageNumber, pageSize)); } I'm using PagedList.MVC (from NuGet) and...

ViewData Compilation Error : BC30203: Identifier expected

javascript,c#,jquery,html,asp.net-mvc
I have code below. public ActionResult PatrList(decimal PAT_ID) { ViewData["PAT_ID"] = PAT_ID; return View(); } <script type="text/javascript"> $(document).ready(function () { var PAT_ID = '<%= ViewData["PAT_ID"].ToString() %>'; $("body").data("PAT_ID", PAT_ID); }); </script> Unfortunately, I got Compilation Error : BC30203: Identifier expected. ...

How to store a string in xml file and use it in _Layout in MVC

c#,xml,asp.net-mvc,asp.net-mvc-4
I'm new here. I've started working my own forum system recently to use as a portfolio. Decided to let the admin of the website set his own name and description for the forum. So first thought was use .ini file to put the string there but C# does not support...

MVC5 - How to get results that span multiple entities

asp.net-mvc
Writing my first MVC app and using VS2013 and SQL Server 2008 R2, EF6 and a database first approach. I have all the basics working for my app, but not sure how to approach this issue. I have a jobs table (JobID is PK) and an items table (with JobID...

Is it possible to add views to deployed .NET MVC Razor site

asp.net,.net,asp.net-mvc,razor
Is it possible to add Razor views to a deployed .NET MVC site? How would you do this?

How to create an input (editorfor) for a field not in the model

c#,asp.net-mvc,entity-framework,asp.net-mvc-3,razor
I have the following on my EDIT view @model Inspinia_MVC5.Areas.GlobalAdmin.Models.Empresa @{ ViewBag.Title = "Edit"; Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml"; var camposAdicionalesEmpresa = (List<Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad>)ViewData["CamposAdicionalesEmpresa"]; var valoresCampoAdicionalesEmpresa = (Dictionary<string, string>)ViewData["ValoresCampoAdicionalesEmpresa"]; } and my controller is like this: public ActionResult Edit(int? id) { var listFields = from b in...

SignalR Service Broker with data from SQL View, does it work? MVC 5 ASP.NET

sql,asp.net-mvc,signalr,service-broker
I've used SignalR with some Databases in SQL in my MVC 5 web application to update the Webpage when table data is modified. My question is... Can I use a MessagesRepository that uses a SqlCommand to a SQL View? Does a SQL View fire a Service Broker event? I'm very...

How to iterate over @Model.ICollection in Java Script function?

javascript,.net,asp.net-mvc,razor,icollection
I have a @Model.LoginCoordinates where LoginCoordinates is ICollection<Coordinates>. The Coordinates class: public class Coordinates { public int Id { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } } Inside the view in I have: <script> function f(){ for (var i =...

Multiple Posted Types asp.net 5 MVC 6 API

c#,asp.net,asp.net-mvc,asp.net-5,asp.net-mvc-6
I can use [FromBody] for single type , but is there any way to use multiple? From the searching and reading I've done there is not a way, but i don't know if a way has been added in MVC 6. If not, where would be best to start with...

Can I check if action is a child action in a view?

c#,asp.net-mvc,razor
I know that I can check if an action is a child action inside a controller, store the result in ViewBag or elsewhere and pass this information to the view, but assuming I don't want\can't modify the controller, is there some way to check if the current action is a...

How to programically collapse or expand Kendo Grid Group by values in row

jquery,asp.net-mvc,kendo-ui,kendo-grid
I have a requirement to default a grouped grid to collapsed state UNLESS it contains a row with a certain value (Status == "Closed"). I got this far but fell down because the dataView only contains an array of rows of the grouped field not the rows as I've seen...

ASP.NET MVC DropDownList NullReferenceException

c#,asp.net-mvc,razor
Im having a problem with my dropDownList giving me a NullReferenceException and I don't know why. I want to post a post where you can choose with the DropDownList which Category it belongs to. Here is some of my code: PostModel public class Post { [Key] public int PostID {...

UTC Time different on servers in different timezones?

c#,sql-server,asp.net-mvc,datetime,timezone
On my dev server I save a value called "ScheduledDateUtc" date to sqlserver e.g. 24-11-14 09:00:00. I also save a value called "UtcOffset" and calculate the "ScheduledDateLocal" like so: var ScheduledDateLocal = ScheduledDateUtc.AddHours(UtcOffset); //a negative offset would be deducted and a positive offset would be added On my dev server...

Cannot get data using LINQ in MVC

c#,asp.net-mvc,linq,asp.net-mvc-4
I'm trying to get data in autocomplete from JsonResult Action Method in my controller. I cannot query data with LINQ, I'm sharing code please guide me. Action Method public class VehicleController : Controller { private readonly IService<Vehicle> _service; public VehicleController(IService<Vehicle> service) { _service = service; } public JsonResult AutoComplete(string term)...

Controller with same structure not working using an interface

c#,asp.net-mvc,interface,datacontext
I have created 8 models and controllers respectively for my Project using the same structure, however now this structure is not working. It is giving me this error: The current type, HelpDesk.Contracts.Repositories.IRepositoryBase`1[HelpDesk.Model.Knowledgebase], is an interface and cannot be constructed. Are you missing a type mapping? Here is my interface: namespace...

.NET MVC: Finding default Bootsrap JavaScripts

javascript,asp.net-mvc,twitter-bootstrap
In an out-of-the-box implementation of an MVC app using Bootstrap in Visual Studio 2013, there seems to be some javasvript that works on this element: <li role="presentation" class="dropdown"> .... </li> When that element is clicked, there is, somewhere, some JavaScript that changes the class in this element to: <li role="presentation"...

Dependency injection with unity in a class library project

c#,.net,asp.net-mvc,dependency-injection,unity
I am new with dependency injection pattern. That's why little confused about few things. Scenario: I have a class library project called 'MailCore'. This project has interface and classes that perform all email sending stuff. I have a mvc project 'The site'. It uses the 'MailCore' project to send email....

Adding where clause to IEnumerable Select

c#,asp.net-mvc,linq
I have the following line of code in my controller that selects the id's of the interests shown within a view (they are listed down the page). IEnumerable<int> interestIds = viewModel.ExistingInterests.Select(x => x.InterestId); However I want to be able to add a where clause to the select section. In ExisitingInterests...

ASP.NET httpHandlers & handlers

asp.net,asp.net-mvc
I am confused about httpHandlers in system.web and handlers in system.webServer. What is the difference between these two configuration? And how and when to use them? Actually another question is for modules as well: httpModules in system.web and modules in system.webServer...

How to add validators for @Html.TextBox() without model

asp.net-mvc,asp.net-mvc-4
This is a part of my view @model bhavin.Models.Employee @using (Html.BeginForm("BuynowForm", "Home")) { <div class="form-group"> <label>Billing Address</label> @Html.TextBox("bill_address", null, new { @class = "form-control valid" }) </div> <p> <input type="submit" value="Submit" class="btn btn-primary" /> </p> } I want to add required validation to it. The billing_address textbox is not a...

How to use ajax to post json string to controller method?

jquery,asp.net-mvc,visual-studio-2013,asp.net-mvc-5
I want to be able to post a json string to a control action but it's always receive the string as null. If I create a view model for the controller method, it works, but that's not what I want since there will be too much view models to maintain....

How to Convert a Time to local Time in Different TimeZone

c#,asp.net,asp.net-mvc,timezone,timezoneoffset
Currently i am working on a chat project from where many users can communicate through each other sitting across the globe. ie: Different TimeZone. eg. 1st in India 2nd in America 3rd in Russia 4th in Australia I am saving my message sent time into database as DateTime.Now.ToUniversalTime() Issue i...

Fetching data from remote SQL server

asp.net,sql-server,asp.net-mvc
I have developed a asp.net web application using visual studio 2010. I'm using SQL server 2008 as database. I need to fetch data from one of the remote server through LAN connection and have to store to my database through C# code. I am beginner to web development using asp.net...

Angularjs resource with scope parameter

javascript,asp.net-mvc,angularjs,single-page-application
My problem is the following: I am trying to call resource with the following parameter and I get the following error: [$resource:badcfg] I tried fixing this in the past 3 hours and I cant seem to make it work. So, if i call it like this: $scope.komintent = Fakturi.komintenti.get({ id:...

Setting up routing when RemoteAttribute specifies AdditionalFields

c#,asp.net,asp.net-mvc,asp.net-mvc-4
How to configure actions if I specify AdditionalFields for validation via RemoteAttribute to handle possible optional additional fields? Currently I try to have actions for possible combinations of optional fields and it does not work as show below. I have a form that is bound to a model and one...

Mvc Remote Attribute is sending “undefined” in query string

c#,asp.net,asp.net-mvc,asp.net-mvc-4
I'm trying to remote validate some code and for the parameter, its passing undefined in as a parameters. Here is my validation code: [OutputCache(Location = OutputCacheLocation.None, NoStore = true)] public class ValidationController : Controller { public JsonResult IsUserNameAvailable(string userName, int? UserId) { var users = new BusinessLayer.BdsAdmin.Users(); if (UserId ==...

MVC route attribute no controller

asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing
I'm building an intranet where I have the following home controller: [Route("{action=index}")] public class HomeController : Controller { public ActionResult Index() { return View(HomeModelBuilder.BuildHomeModel()); } public ActionResult FormsHome() { return View(HomeModelBuilder.BuildFormsHomeModel()); } } I'm trying to get my forms homepage to have a url of http://intranet/forms so I thought I...

How to get the client ip address in asp.net mvc?

asp.net,asp.net-mvc
Hi I am using a payment gateway.To which I have to pass the ip address of the client ( someone using my website) . How to get it? I tried to use the following code when I run my project in local system System.Net.Dns.GetHostByName(Environment.MachineName).AddressList[0].ToString(); and i got some value. But...

IndexOutOfRange in while loop and route error

c#,asp.net,asp.net-mvc
I am using a while loop which gives me an indexoutofrange error. I do not understand why this code would give me this. This is what I have in my view: @{ int i = 1; while(i < 6) { <li class="item" id="[email protected]"><img src="[email protected][i].image_name" /></li> i++; } } Also, when...

How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?

javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing
I have this ActionLink. @Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new [email protected] = "menuLink"}) I have to set routeValues to null because I don't know the value at compiletime. They are recieved from the selectedvalue of some dropdowns at runtime. Hence, I am trying to augment the routevalues at runtime with...

Trying to delete user from database by Username in .NET MVC

c#,sql,.net,asp.net-mvc
I am new to C# MVC and am having trouble figuring out how to make the connection to the specific user I am trying to delete. I have a table that reads the users in by username (user.UserName) @using (Html.BeginForm("DeleteUser", "Manage", FormMethod.Post)) { <table class="table"> <tr> <th>Username</th> <th>Role</th> </tr> @foreach...

Binding my view model to a view causes all check boxes to be checked

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I'm having an issue where my all the check boxes rendered in the view are coming out checked. I put a breakpoint at the line where my view model is constructed and through the debugger, I can see that some values are set to "true" and others are set to...

VS2013 Is Not Compatible With VS2015 Project Type

asp.net-mvc,visual-studio-2013,asp.net-mvc-6
I am using Visual Studio 2013. But when i open the MVC project code in Github: https://github.com/betimer/Mvc I found that the solution was built on the new type (project contains: xxx.xproj + xxx.json) (I think they are VS 2015 types) Is there any way to let my VS 2013 compatible...

Output Raw String in ASP.NET MVC Razor [duplicate]

c#,asp.net-mvc,razor
This question already has an answer here: Emitting unencoded strings in a Razor view 4 answers I have a site built with ASP.NET MVC. I have a string in my view model that looks like this: ViewBag.Text = "{\"1\":{\"1\":\"John\",\"2\":\"Bill\",\"3\":\"Paul\"},\"3\":{}}"; I want to output this into my view like this:...

Different output when run on Azure than on local build

c#,asp.net-mvc,azure,encoding
I have a C#, .NET MVC 4.5 web app with an action method which calls out to a web service with a query string parameter. Something like "[email protected]" I'm using Encoding.UTF8 and my return code looks like this: return Content(responseText); This outputs as: 6^.a308666-86 which is correct. However, when I...

Url.Action Compilation Error : BC30988: Type or 'With' expected

javascript,c#,html,asp.net-mvc
I have code below, I need redirect to an other view page. function patrListClick(PAT_ID) { window.location.href = '<%: Url.Action("PatrList", "Patr", new { id = "_id_" }) %>'.replace('_id_', PAT_ID); } Unfortunately, I got compilation error. ...

Creating a viewmodel on an existing project

c#,asp.net,asp.net-mvc
I am trying to add a viewmodel to a project because I want my view to use two separate models. I've looked at different tutorials trying to learn how to do this but I am having some trouble. Before, the view was strongly binded(typed?) to the Person model, but now...

OnAuthorization being called multiple times

c#,asp.net-mvc
I have a custom filter: public class SetAuthFilter : IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { //do something } } In the Application_Start() under the Global.asax: GlobalFilters.Filters.Add(new SetAuthFilter()); The above codes will be called everytime an action is invoked. However, in my _Layout.cshtml, I have 2 different "BaseController", something like:...

Deserialize JSON into Models that render in partial view (restsharp or any other method)

c#,json,asp.net-mvc,restsharp
I've never dealt with deserializing JSON and i'm just not getting it. I call an API and get JSON returned, I then want to use the JSON data my partial view. My thought process is get JSON, deserialize into Model, pass model to view and away we go. I've currently...

A specified Include path is not valid. The EntityType '*Propiedad' does not declare a navigation property with the name 'Nombre'

c#,asp.net-mvc,entity-framework,asp.net-mvc-4,repository-pattern
I am trying to implement unit of work and the generic repository pattern as explained here: http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application My entity Propiedad is like this: public class Propiedad { [Key] public int Id { get; set; } public virtual Entidad Entidad { get; set; } public string Codigo { get; set; }...

Why is my View not displaying value of ViewBag?

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I have a little blog application with posts and tags. This is my model for Post: namespace HelloWorld.Models { public class Post { [Required] [DataType(DataType.Text)] public string Title { get; set; } [Required] [DataType(DataType.MultilineText)] public string Description { get; set; } [Required] [DataType(DataType.DateTime)] public DateTime PostDate { get; set; }...

ASP.net HTTP Post when auto-incrementing row Id

sql,asp.net,asp.net-mvc,http
I am working in ASP.net with a Web API allowing HTTP Posts to update a mapped SQL database. I want the Id to be automatically increment by one every time a new row is inserted. The table definition is this: CREATE TABLE [dbo].[PoolTests] ( [Id] INT IDENTITY (1, 1), [SiteID]...

How do I create an editor template that works with existing data?

c#,asp.net,asp.net-mvc,forms,razor
I created an editor template to display text boxes included in a form. @model WebApplication1.Models.PersonViewModel <input type="text" class="form-control" name="@ViewData.TemplateInfo.HtmlFieldPrefix" value=""/> I simply want to include the 'form-control' class in all my input text boxes used to collect data for this model. public class PersonViewModel { [UIHint("_TextFormControl")] public string FirstName {...

How to enable multiple login tries in asp.net forms authentication?

c#,asp.net,asp.net-mvc,authentication
I have a MVC project with forms authentication. Basically it works fine: The user wants to access a controller with Authorize-Attribute and gets redirected to login-page if not authenticated. On redirect the parameter returnUrl gets forwarded as well. However, in case the first try of the login fails, the return...

DropDownListFor always return null to controller

c#,asp.net-mvc
My ViewModel looks like this: public class ProjectViewModel { public ICollection<Project> Projects { get; set; } } My controller: [HttpPost] [Route("ChooseProject")] public ActionResult ChooseProject(Project projects) { return RedirectToAction("Index", "Application"); } And finally my view: @using ServicePortal.Web.Controllers @model ServicePortal.Web.Models.ProjectViewModel @{ Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.Title = "Choose project"; } <div class="pure-form pure-form-aligned">...

devenv.exe hogs CPU when debugging

asp.net-mvc,visual-studio-2013
Short version: When I debug ASP.NET MVC apps in VS2013 and try to edit razor views or css files, the CPU usage of devenv.exe skyrockets to the point where VS becomes unresponsive. Browser link is turned off, yet this still happens. Restarting debugging doesn't help, restarting VS doesn't help, restarting...

Request.Form is null on making button as disabled

c#,asp.net-mvc,razor
I have two buttons on my screen i am handling with one method : Request.Form["Approve"] becomes null as i have disabled the button, how i can get the value of Request.Form["Approve"] after disabling the button. @if(ViewBag.RequestAlreadyProcessed) { <input type="submit" class="btn btn-primary btn_box" value="Approve" name="Approve" disabled="disabled" /> <input type="submit" class="btn btn_secondary...

ASP.Net Using @Html.ActionLink() for Navbar buttons

c#,asp.net-mvc
I'm working on Visual Studio MVC currently. As MVC helps to create codes automatically for some functions. I am trying to understand what does this sentence of code means. I understand the first two parameters, but not the third one. -----> @Html.ActionLink("Text Displayed", "Method name in controller", "Third???") My code...

Why PartialView cannot reload with Ajax in MVC

ajax,asp.net-mvc,asp.net-ajax,asp.net-mvc-partialview,ajax.beginform
I use a popup window to create a new record and I render a view inside the window. In addition to this, I call a partialview in this view according to the selectedindex of a combobox in it. I can successfully post the form to the Controller and return it...

How to get routevalues from URL with htmlhelpers or JavaScript?

javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-routing
I have this MVC MapRoute routes.MapRoute( name: "Authenticated", url: "{controller}/{action}/{foo}/{bar}", defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" } ); And URL http://localhost/mysite/controller/action/2/1 How can I with JavaScript recieve the 2 and 1? I would prefer a solution with as little substring work...

MVC/Razor: Error at Viewbag.Title

c#,asp.net-mvc,razor,asp.net-mvc-5
I have two methods: public ActionResult Index() { var propList = db.Properties .Where(x => x.SiteVisibilityFlags.HasFlag(Enums.SiteVisibilityFlags.Corporate) || (x.SiteVisibilityFlagsOverride == true && x.SiteVisibilityFlagsOverrideValue.HasFlag(Enums.SiteVisibilityFlags.Corporate))) // just ones visible to 'Corporate' .ToList(); // Use view model var pDVMs = DomainModelsToViewModels(propList); return View(pDVMs); } public ActionResult Region(string id) // (regionId/marketId) { // make sure to...

File IO Close() method error in ASP.NET MVC 6

asp.net-mvc,asp.net-mvc-6
I am doing a simple file IO in MVC6. I have added System.IO NuGet package. However, it gives me compile time error. VS IDE doesn't show any red mark when I type the code. The Close() method also appears in intellisense. Please help! My Code StreamWriter writer = System.IO.File.CreateText("some_valid_path"); writer.WriteLine("test");...

Show/hide tinymce with radio buttons

c#,asp.net,asp.net-mvc,tinymce
I try to show/hide a tinymce with radobutton. Like yes/no. So there are two radio buttons. yes - will show the tiny mce and no will hide the tinymce. I have this: showing tiny mce: <div class="form-group"> @Html.Label(Resources.Entity.Product.PdfMessage, new { @class = "text-bold control-label col-md-2" }) <div class="col-lg-6 col-md-8 col-sm-10...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity
I'm trying to learn Claims for MVC 5 OWIN login. I try'ed to keep it as simple as possible. I started with the MVC template and inserted my claims code (see below). I get an error when I use the @Html.AntiForgeryToken() helper in the View. Error: A claim of type...

How to hide columns in Kendo Grid when editing in a popup

asp.net-mvc,kendo-ui,kendo-grid,kendo-asp.net-mvc
I use Telerik Kendo Grid editing-inline. I want to hide certain columns when editing popup the number of columns....

How to get tables from database first approach without .tt and edmx files?

c#,asp.net-mvc,entity-framework,entity-framework-6
I am working on database first approach. I followed the following link https://msdn.microsoft.com/en-us/data/jj200620 I'm able to get the cs files. But cs file are coming under edmx folder. but I want to get cs file directly as similar as code first approach I am using entity framework 6 and mvc...

Http Get Request for IpDBInfo using an IP Address

c#,asp.net-mvc,geolocation,ip
I am working on a web application and it needs to track a location using an IP Address and I am new to sending requests to some APIs and getting a response from them. I was able to retrieve IP address of the user using Request.UserHostAddress and was able to...

How to format label in ASP.net chart control

c#,asp.net,asp.net-mvc,c#-4.0,reporting-services
I have created a column chart in asp.net. I am showing the date on x-axis. At the moment the date is shown as dd/mm/yyyy. All I need is to show the date as dd-mm-yy and ideally Weekday, dd-mm-yy e.g. Monday, 12-05-15. <asp:Chart ID="Chart1" runat="server" Height="400px" Width="900px" BorderWidth = "1"> <Series>...

Kendo UI ASP.NET MVC ListView fails when trying to add or edit items

c#,asp.net-mvc,listview,razor,kendo-ui
I'm struggling to set up a ListView which allows me to add new records and to update existing ones. Loading the items for the list works like a charm. Also showing the only relevant information Id and Line works perfectly. Two problems: 1. Adding a new item to the list:...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net
My Windows service is in the same solution as a MVC project. The MVC project uses a reference to SignalR Client which requires Newtonsoft.Json v6 + the Windows service uses System.Net.Http.Formatting, which requires Newtonsoft.Json version 4.5.0.0. I assumed this would not be a problem, as I could just use a...

IDENTITY_INSERT is set to OFF in MVC application

sql,asp.net,asp.net-mvc
I am trying to create a new employee in MVC 5. I used CRUD to generate views and models. I edited a few lines of code and I get this error: Cannot insert explicit value for identity column in table 'Table' when IDENTITY_INSERT is set to OFF. Where I got...

How to use Autofac to inject specific implementation in constructor

c#,asp.net-mvc,dependency-injection,autofac
I have two classes that take a ILastActivityUpdator as a constructor parameter: UserService and AnonymousUserService. public AnonymousUserService(ILastActivityUpdator lastActivityUpdator) { if (lastActivityUpdator == null) { throw new ArgumentNullException("lastActivityUpdator"); } this.lastActivityUpdator = lastActivityUpdator; } And similar as above for UserService: public UserService(ILastActivityUpdator lastActivityUpdator) { if (lastActivityUpdator == null) { throw new ArgumentNullException("lastActivityUpdator");...

Writing to .config files

asp.net-mvc,web-config,configuration-files,nlog
I am having an issue somewhat similar to this question: C#: Config file error BACKGROUND My situation is this: I am using NLog and I have setup a Database target. My app shows an installation page on first run from which I build a connection string for other purposes but...

MVC HTML Helpers: Get all validation attributes

c#,asp.net-mvc,validation,html-helper
When it comes to making custom helpers, how can we get the value for the validation attributes (client-side validation)? for example the built in helpers do something like this: <label class="control-label " for="Starts">Starts</label> <span class="field-validation-valid text-danger" data-valmsg-for="Starts" data-valmsg-replace="true"></span> <input class="form-control text-box single-line" data-val="true" data-val-date="The field Starts must be a date."...

Dynamically adding controls in MVC4

asp.net-mvc,asp.net-mvc-4
I am currently working on creating an MVC4 application where I want controls to be generated automatically from the database rows. I have the table in my database containing the questions and the control type in which it should be answered by the user. I am just thinking of a...

Razor foreach loop loses item property

c#,asp.net-mvc,razor
I am creating a dynamic radio button group based on a selectlist within my model. when I pass a model to the View I want it to have the radio button selected based on the selected property of the selectlist. Here is what I have in the View: @foreach (var...

which approach is best for GET,POST using Rest API [closed]

c#,jquery,asp.net-mvc,angularjs
i am using rest api to fetch and save the data in database using jquery or angularjs, but i want to ask you about which approach is best for doing this. using jquery to post the data using angularjs to post the data using c# code behind to post the...

Unable to find the auto created Database

c#,asp.net,asp.net-mvc,entity-framework
I have created simple ASP.NET MVC4 application using EntityFramework Code first approach. The entity class is as below: public class Album { [Key] public int AblumId { get; set; } public decimal Price { get; set; } public string Title { get; set; } } public class MusicContext : DbContext...

how to interpolate property names with razor

c#,asp.net-mvc,razor
Let's suppose I have an array of objects myObjects whose string properties are Alpha, Beta, Gamma, ... In my View I could display the content with Razor like this <ul> @foreach(obj in myObjects){ <li>@obj.Alpha</li> <li>@obj.Beta</li> <li>@obj.Gamma</li> ... } <ul> But if I want to compact the code, passing an array...

How to solve error in Configuration.cs in code first migration

c#,asp.net-mvc,entity-framework
I was setting up code first migration for model changes from Package Manager Console which creates seedmethod in Configuration.cs. i placed my code in Seed method and it shows error at context.Movies.AddorUpdate(----- it says : The type arguments for method 'System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate(System.Data.Entity.IDbSet, params TEntity[])' cannot be inferred from the usage. Try...

ASP.net MVC HTTP Request error with payload

asp.net,json,asp.net-mvc,http
I am creating an ASP.net MVC website with a RESTful API to a SQL database. I have implemented a controller which holds the HTTP commands. One of the commands is a POSTcommand: // POST: api/PoolTests [ResponseType(typeof(PoolTest))] public IHttpActionResult PostPoolTest(PoolTest poolTest) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.PoolTests.Add(poolTest); db.SaveChanges(); return...

Preventing a class method from executing more than once at a time

c#,asp.net-mvc,dependency-injection,singleton
I have a asp.net mvc controller that when executed calls a method in a service class to open a file and start the import of records into a database. I'd somehow like to restrict this method or class so that another instance can't be created and prevent the method from...

HTTP Error 403.14

asp.net-mvc,visual-studio-2013
I'm developing my MVC 5 app using VS 2013, it was working fine, but suddenly it's giving the following error. HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory. I've already read this post, and it didn't solve the problem. I've...

C# Refactoring gigantic switch statement for ordering with LINQ

c#,asp.net-mvc,linq,dry
My problem is repetitive code: a not so DRY switch statement. So I have a table with 12 columns that can be ordered by descending or ascending on click. My current solution is the use of a switch statement that checks which column was clicked. The sortable properties: This is...

Strange situation, Visual Studio debugging ran through action to view but nothing returned to browser

c#,jquery,ajax,asp.net-mvc,razor
I have encountered a very strange problem. Basically, there is a Delete ActionLink. Once clicked, the code checks the condition, checks true/false, stays on current page or goes to Delete view. I have posted the solution for this scenario and got some very helpful replies. I worked on it and...

Database object with different data

sql,asp.net,asp.net-mvc,database,entity-framework-6
I'm making a web page in ASP.NET MVC which compares prices from different shops. I have a one-to-many with products and the shops, where the SHOP has one PRODUCT and a PRODUCT has many SHOPs, the problem is that the product is the same but the price is different. Example:...

Getting a JavaScript object into my controller: What am I missing here?

c#,asp.net,ajax,json,asp.net-mvc
I'm getting a 500 (Internal Server Error) when I try to run $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); return xhr; }, type: 'POST', url: [email protected]("MyAction","MyController")', data: fi, contentType: "application/json; charset=utf-8", dataType: "json", // dataType is json format success: function(retJson) { // ... } }); where fi is...

ASP.NET MVC posting list from view to controller

c#,.net,asp.net-mvc,razor
I have a view model in my ASP.NET MVC application: public class FiltersViewModel { public IEnumerable<SelectListItem> AvailableFilters { get; set; } // fills a drop down menu public IList<TechnologyFilter> TechnologyFilters { get; set; } public IList<ContractTypeFilter> ContractTypeFilters { get; set; } public FiltersViewModel() { this.TechnologyFilters = new List<TechnologyFilter>(); this.ContractTypeFilters =...

check if file is image

c#,asp.net,asp.net-mvc
I want to check if file is image. and then you will see a link where you can see the image. But the link only has to appear if file is link. I try it like this: if (!String.IsNullOrEmpty(item.FileName)) { var file = item.FileName; string[] formats = new string[] {...

Knockout JS Validation not working

javascript,asp.net-mvc,knockout.js
I am a newbie in Knockout JS. i want to apply validations in KO. i have used plugin knockout.validation.min.js . I have implemented it like this but not working My View Model $(document).ready(function myfunction() { ko.applyBindings(new EmployeeKoViewModel()); }) var EmployeeKoViewModel = function () { var self = this; self.EmpId =...

Use a call Ajax to send an Array of string to mvc Controller

javascript,jquery,arrays,ajax,asp.net-mvc
i'm trying to get the values from the a table column, I put it in an array then send it to my controller. Something very strange happens, you'll see below : Here is my JS code : var result = []; $('td:nth-child(' + columnNbr + ')').each(function () { var t...

How to get Display Text from EnumDropDownListFor on post?

c#,asp.net-mvc,enums,html-helper
Is there a way to get DisplayName (Text) from EnumDropDownListFor helper for enum? Enum: public enum PartnersGroup { [Display(Name="Partner_SystemsGroup",ResourceType=typeof(Global) )] SystemsGroup, [Display(Name="Partner_SoftwarePartners",ResourceType=typeof(Global))] SoftwarePartners, [Display(Name="Partner_IntegrationPartners",ResourceType=typeof(Global))] IntegrationPartners, } Model public class Partner { public PartnersGroup PartnersGroup { get; set; } } Controller // GET: Partners/Create public ActionResult Create() { ---- return...

Inherited Property of Model is always returning Null Value

c#,asp.net,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-5
I have a view which displays a radiobutton list on left side of the page and it also loads a partialview on right side of the page which consist of various filters to be selected before displaying a report in a popup window. The problem is that the property named...

Getting 302 response headers from Ajax.BeginForm?

c#,jquery,asp.net,ajax,asp.net-mvc
I have a MVC action that can either return a RedirectToAction (302) or a partial view. I'm using Ajax.BeginForm and an OnSuccess handler to capture the response. My problem is, whenever a redirect response is issued, it seems something (not sure if it's a native AJAX behavior or not) is...

When adding a user to a role in asp.net mvc 4.5, i'm getting an error- “user (user name) not found”

c#,asp.net-mvc
Here is my account login controller. (My "auth" class method returns "user" or "admin" and is logged in accordingly). [HttpPost] public ActionResult Login(string userName, string pass) { Auth auth = new Auth(); if (auth.MyAuth(userName) == "user") { FormsAuthentication.SetAuthCookie(userName, true); return RedirectToAction("Index", "Home"); } else if(auth.MyAuth(userName) == "admin") { FormsAuthentication.SetAuthCookie(userName, true);...

check for value null on razor syntax

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,razor
The following code is failing because propiedadesFormularioDetalle is null. I placed an IF before the block code but still not working, if I remove one of the bracked, then it wont compile @if (propiedadesFormularioDetalle != null) { } <div class="panel panel-default"> <div class="panel-heading">Propiedades adicionales</div> <div class="panel-body"> <dl class="dl-horizontal"> @foreach (KeyValuePair<string,...

Stop Html.Action from being called on Load

javascript,jquery,html,asp.net-mvc
I have below div inside a parent view and the below Html.Action returns a PartialView <div id="preview" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> @Html.Action("GetPrintView", "Connector") </div> </div> I open the above modal using below jquery: $("#printdoc").click(function(e) { e.preventDefault(); $(this).attr('data-target', '#preview'); $(this).attr('data-toggle', 'modal'); }); The issue is,...

Can't get Editor Template to Work

jquery,asp.net-mvc,razor
I'm trying out editor templates and I can't get it work. I'm working off of this tutorial to try and get a jQuery drop calendar to appear for a DateTime? Can anyone see what I'm doing wrong? I changed my code and tested a TextboxFor and it worked out so...

display 3 tables data values

c#,asp.net-mvc
I have three tables in my MSSQL database. I have already created three class files. What I need to do MVC C# index.chtml file display all data result report. Below my these 3 tables classes only display Region Name but not display deliveryDay.DeliveryDay. It should be display Monday, Friday any...

An optional parameter must be a reference type, a nullable type, or be declared as an optional

c#,asp.net-mvc
I am passing a value from controller to View using ViewBag and storing it in a variable. Then from the same view I am sending the value back to Controller stored in the variable. Earlier it used to work but recently it started giving me below error. The parameters dictionary...

Avoid EF update the null image to database in .Net MVC

asp.net-mvc,entity-framework,null,edit,httppostedfilebase
In my SachController, there is an Edit method like below. In the view, there are several textbox and one file-input for upload image object. Sometime, user doesn't want to change the image and they just don't select a new image. And the image (HttpPostedFileBase) is null. How can I avoid...

How to upgrade mvc2 to mvc5?

asp.net-mvc,asp.net-mvc-2,asp.net-mvc-5
I've got an old project from a friend that he wants me to do redo. How ever that project is written in ASP.net mvc2. So When I try to open it in visual studio 2013 I can errors. Saying the file is incompatible. How would I go ahead and fix...

ASP.NET MVC Client side time convert from model

javascript,asp.net-mvc,model
My cshtml page contains the following code for DateTime, which is some server time fetched from sql. <tbody> @{ foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.someDate) </td> The type of the someDate property is DateTime. I would like to show the time in respect to client/browser...

Best approach to upgrade MVC3 web app to MVC5?

c#,.net,asp.net-mvc,asp.net-mvc-5
I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

ASP.NET EF6 - 2 Tables & 1 Link Table

c#,sql-server,asp.net-mvc,entity-framework
I am not the most fluent with ASP.NET/EF, so I am having a bit of a hard time trying to find the best way to accomplish what I need to get done. I'm trying to create a CRUD with an already existing database. Instead of the Employees table having specific...

Checkbox to be checked on having value Y

asp.net-mvc,knockout.js
I have a checkbox bound to a viewmodel's observable property, whose value will be Y or N. I want the the checkbox to be checked when the value is Y and unchecked when the value is N. How to achieve this? I am able to achieve it if the value...

Get a single text value using linq

c#,asp.net-mvc,linq,entity-framework,asp.net-mvc-3
I am using this line to return a value, but instead its getting a True var valor = valoresCampoAdicionalesEmpresa.Select(p => p.Key == propiedad.Nombre).First(); This the view data passes from the controller var valoresCampoAdicionalesEmpresa = (Dictionary)ViewData["ValoresCampoAdicionalesEmpresa"]; public ActionResult Edit(int? id) { var listFields = from b in db.Propiedades where b.Entidad.Nombre ==...