asp.net-mvc-4,asp.net-mvc-5,asp.net-identity,simplemembership , How to migrate from SimpleMembership to ASP.NET.Identity


How to migrate from SimpleMembership to ASP.NET.Identity

Question:

Tag: asp.net-mvc-4,asp.net-mvc-5,asp.net-identity,simplemembership

Migrating from MVC4 to MVC5 and want to use ASP.NET Identity too but I am struggling to find anything that covers everything I think I need to do to migrate the Identity. This link suggests all I need to do is create an ApplicationUser and migrate the data, and other web searches give me sql scripts and passowrd hashing advice. But there are other loose ends that I'd like to clear up before I jump in.

First - I have code to initialise the membership system in my Seed method:

if (!WebSecurity.Initialized)
    WebSecurity.InitializeDatabaseConnection(Config.ConnectionStringName,
        Config.UsersTableName,
        Config.UsersIDColumn,
        Config.UserNameColumn,
        autoCreateTables: true);

So that needs to go right?

Second - it looks like I need an IdentityDbContext. So should I change my existing context to inherit that?

i.e. instead of my current code public class SID2013Context : DbContext do this: public class SID2013Context : IdentityDbContext<ApplicationUser>

Will that generate a migration that creates the new tables I need to support ASP.NET Identity?

Once I've done that I should be able to pull in the AccountController, Views, ViewModels and start up code that is generated for an MVC5 project.

Can anyone answer the specific questions here and/or point me to a better resource?


Answer:

I realised that the website I linked to in my question is telling you how to migrate to Identity tables, but still use SimpleMembership. I want to use Identity throughout, so I created an empty MVC application using Visual Studio so that I could copy in the code I wanted and fix it up. Here are the steps I followed to get Login and Logout working:

  1. Added ApplicationUser.cs to my Models project
  2. Added IdentityConfig.cs to my App_Start folder
  3. Added Startup.Auth.cs to my App_Start folder
  4. Added AccountController.cs to my Controllers folder (renamed existing controller)
  5. Added Startup.cs to root folder
  6. Added AccountViewModels.cs to ViewModels folder
  7. Changed my context to inherit IdentityDbContext (it does indeed mean that new tables are created in a migration)
  8. Added the required NuGet packages and fixed up all the namespaces
  9. Project now builds
  10. But Add-Migration gave an error ... "EntityType IdentityUserRole has no key defined"
  11. ....solved that by adding a call to base.OnModelCreating in my override
  12. Add-Migration & Update-Database - adds the tables required
  13. Added my custom fields in UserProfile to ApplicationUser and updated the database
  14. Used sql (in a migration) to copy data from old tables to new tables. Sql included here. NB need to populate SecurityStamp with a Guid to prevent error during Login
  15. That's got Login and Logout working
  16. Removed UserProfile, SimpleRoleProvider and RoleManager classes - replacing the code where necessary.
  17. Removed references to WebMatrix.Data and WebMatrix.WebData dlls
  18. Removed <roleManager enabled="true" defaultProvider="simple"> and <membership defaultProvider="simple"> from web.config

Sql used in step 14:

INSERT INTO dbo.aspnetusers (id
, email
, emailconfirmed
, passwordhash
, securitystamp
, phonenumber
, phonenumberconfirmed
, twofactorenabled
, lockoutenddateutc
, lockoutenabled
, accessfailedcount
, username
, organisationid
, firstname
, lastname
, inactive)
    SELECT
        u.id,
        u.username Email,
        m.isconfirmed EmailConfirmed,
        m.password PasswordHash,
        --SignInManager.PasswordSignInAsync (used in Login method) 
        --throws an exception http://stackoverflow.com/a/23354148/150342
        NEWID() SecurityStamp, 
        u.telephone PhoneNumber,
        CASE
            WHEN u.telephone IS NULL THEN 0
            ELSE 1
        END PhoneNumberConfirmed,
        0 TwoFactorEnabled,
        NULL LockoutEndDateUtc,
        0 LockoutEnabled,
        m.passwordfailuressincelastsuccess AccessFailedCount,
        u.username,
        u.organisationid,
        u.firstname,
        u.lastname,
        u.inactive
    FROM dbo.userprofiles u
        INNER JOIN dbo.webpages_membership m
            ON m.userid = u.id
    WHERE NOT EXISTS (SELECT
        1
    FROM dbo.aspnetusers
    WHERE id = u.id)

INSERT INTO dbo.aspnetroles (id
, name)
    SELECT
        roleid,
        rolename
    FROM dbo.webpages_roles r
    WHERE NOT EXISTS (SELECT
        1
    FROM dbo.aspnetroles
    WHERE roleid = r.roleid)

 INSERT INTO dbo.aspnetuserroles (userid
    , roleid)
        SELECT
            userid,
            roleid
        FROM dbo.webpages_usersinroles ur
        WHERE NOT EXISTS (SELECT
            1
        FROM dbo.aspnetuserroles
        WHERE userid = ur.userid
        AND roleid = ur.roleid)

Related:


C# entity framework MVC second run error


entity-framework,asp.net-mvc-4,localdb
I am creating db and initializing data with code below, if DB doesnt exist, it creates db and populate it, when I run application second time I get error Cannot drop database "aspnet-app" because it is currently in use. Application_start, with initializations protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);...

How to Implement Dependent Dropdownlist in MVC4 Razor and using SQL server also


sql-server,asp.net-mvc-4,razor
I've 2 Dropdownlist called States and Country. but only the States DDL(DropdownList) will be enable the country DDL will be diable. when I select a option in States which is already stored in SQL. The Country DDL Should Show the Selected state's Country automatically from DB. Please help Me..... Ex:If...

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 ==...

C# mvc4 - direct URL to controller


c#,asp.net-mvc-4,url,redirect
I have an external URL that points directly to a function in my controller but when I click on it for the first time, instead of reaching the page, I get to the home page. However, on the second click (and the following ones), I can reach the desired page....

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....

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...

C# Using Bool, how to check a double is truly divisible by another number? [duplicate]


c#,asp.net-mvc-4
This question already has an answer here: How can I calculate divide and modulo for integers 4 answers Is there a way of checking that a value is wholly divisible by another number, for example 1000 divided by 100 would be true, but 1115 divided by 100 would be...

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; }...

Embedding a Silverlight App into a MVC


c#,asp.net-mvc-5,silverlight-5.0
I decided to convert the WPFs into a Silverlight applications. My only problem is trying to get it to display the silverlight application in my MVC web browser. I added all of my silverlight projects into my MVC project. I am just not getting it to show my silverlight application....

404 when converting asp.net mvc app to angularjs


c#,asp.net,asp.net-mvc,angularjs,asp.net-mvc-4
so I have my full asp.net mvc project working which renders perfectly fine. Then I am trying to convert it to use angular for the UI and web api for the backend. In the views folder I added an index.html file with this code: <!-- * INSPINIA - Responsive Admin...

Web API AuthorizeAttribute does not return custom response


c#,asp.net-web-api,asp.net-mvc-5
How can I make IsAuthorized return my custom object while function returns false? In my WebAPI project I have a class like; public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse() { code = (int) Constants.ErrorCodes.InvalidCredentials, data = "InvalidCredentials.", StatusCode = HttpStatusCode.Unauthorized...

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...

MVC Push notification from server to client side


asp.net-mvc-4,push-notification
This question may sound lame but. Is there any technique to send push notificaiton from server to client side, regarding the server status. For Example: While Login Notification in Client Side in sequence: Validating User ... Validating Digital Certificate ... Sorting downloadable file ... Preparing to download ... If its...

string.Format is not giving correct output when INR currency symbol (Rs.) come to display


c#,asp.net-mvc-5,devexpress
While display bank transaction data to INR currency symbol (Rs.), output is not coming correct way. I need to display currency symbol along with 2 decimal points with thousand separator. I have tried so far1: column.PropertiesEdit.DisplayFormatString = string.Format("{0} #,0.00", Model.CurrencySymbol); I have used DevExpress MVC GridView. Current output when INR...

Unable to make parent li active on click of child li with bootstrap in mvc4


c#,asp.net,asp.net-mvc-4,c#-4.0
I have search and try different method like using JQuery Helper class etc but i can't find solution for my scenario. My code is below I want Active li when i user select and page refresh <aside class="main-sidebar" style="background: #102C4B none repeat scroll 0% 0%;border-right: 1px solid #DCE1E4;"> <section class="sidebar">...

Display value of a textbox inside another textbox using AngularJs on button click


angularjs,asp.net-mvc-4
New in AngularJs. Finding it complex a little. I have created two text box and a button. Now I want, first I will write something inside the first text box. Then I will click on the button. After that the value of the first text box will get displayed inside...

ASP .Net MVC get decorated roles for unathorized request


c#,asp.net,asp.net-mvc,asp.net-mvc-4
In MVC we decorate actions using AuthorizeAttribute. When a given user is not authorized for a particular action it calls HandleUnauthorizedRequest method. I have overridden this method in my custom class called CustomAuthorizeAttribute that inherits from AuthorizeAttribute. With in the scope of my overridden HandleUnauthorizedRequest method how do I get...

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...

Linq Conditional DefaultIfEmpty query filter


c#,linq,asp.net-mvc-5,linq-query-syntax
I have a query as below: bool variable = false//or true var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user = u, profile = p }; This...

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...

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; }...

How to append Urls in angular routing?


asp.net,angularjs,asp.net-mvc-5,angularjs-ng-repeat,angular-ui-router
How to do url(string) cocatenation in angular routing. Please refer the below snippet to understand my question. app.config(['$routeProvider', '$location'], function($routeProvider) { when('/', { templateUrl: '/AlbumsList.html', controller: 'a1Ctrl' }). when('/albums/:albumName', { templateUrl: 'AlbumsList.html', controller: 'b1Ctrl' }) }) app.controller('a1Ctrl', function($scope, $http) { $scope.albums = function() { //ajax getting data from server }...

Conflicted with the REFERENCE constraint. How to solve this?


asp.net-mvc-4,nhibernate
I catch this GenericADOException exception but some unexpected exception comes again when I do genRep.Update(userW). How can I fix this problem? This is my code: public ActionResult DeleteUser(long? UserID) { GenericRepositoryV2 genRep ; if (!SecurityService.IsLoggedIn(Session)) { return SecurityService.LoginAndRedirect(Request); } try { genRep = new GenericRepositoryV2(); genRep.StartTransaction(); User user = genRep.GetById<User>(UserID);...

Produce different serialized JSON for a given class in different scenarios


c#,json,serialization,asp.net-mvc-5,json.net
Update 1: for reasons I won't go into, I want to avoid having anything other than the properties to be persisted in my entity objects. This means no extra properties or methods... I have an entity called Entity1 with (say) 10 public properties. In one place in my code I...

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...

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)...

Use “Contains” to match part of string in lambda expression


c#,jquery,asp.net-mvc-4,lambda
I have this MVC page where I have three different "input" elements, all the same class, using the jQuery autocomplete. On any one of them I am doing this in the controller: [HttpGet] public ActionResult GetAllItemsEdit(string data, string source) { List<TextValuePair> items = InventoryControlRepository.GetAllItemsTVP(); var result1 = items.Where(item => item.Text.Contains(data.ToUpper())).ToList();...

mvc 4 custom format validator does not show error and allows the form to submit


asp.net-mvc,validation,asp.net-mvc-4
I have the following validator for a MVC 4 view public class IpFormatValidator: ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { ValidationResult resp; if (value != null) { string ip ; IPAddress noUsed ; ip = value.ToString(); if(IPAddress.TryParse(ip, out noUsed)) { resp = ValidationResult.Success; } else { resp...

How detailed should your repository be? Testing issues [closed]


c#,unit-testing,asp.net-mvc-5
In my controller, I have something like this: class HomeController { [AllowAnonymous] public ActionResult Index() { HomeViewModel viewModel = new HomeViewModel(); viewModel.FieldSearchCriteria = new SearchCriteria(); viewModel.Blogs = this.unitOfWork.BlogRepository.GetAllPublishedBlogs(1, 2, "PublishDate", SortDirection.DESC, null).ToList(); viewModel.FieldWanteds = this.unitOfWork.FieldWantedRepository.GetAllFieldWanteds( 1, 2, "CreatedAt", SortDirection.DESC, null ).ToList(); viewModel.Fields =...

Knockout js unable to bind data using observableArray


knockout.js,asp.net-mvc-5
I am trying to display all the employees in the database and I am unable to achieve it. My JS, var EmployeeKoViewModel = function () { var self = this; self.EmpId = ko.observable(""); self.Name = ko.observable(""); self.City = ko.observable(""); self.Employees = ko.observableArray([]); GetEmployees(); function GetEmployees() { $.ajax({ type: "GET", url:...

MvcSiteMapProvider - Enhanced bootstrap dropdown menu


c#,twitter-bootstrap,asp.net-mvc-5,mvcsitemapprovider,mvcsitemap
I'm trying to build a menu like this: For reference I'm using this library https://github.com/behigh/bootstrap_dropdowns_enhancement @Html.MvcSiteMap().Menu("BootstrapMenuHelperModel") @model MenuHelperModel <nav class="navbar" role="navigation"> <div class="container-fluid menu-container"> <div class="collapse navbar-collapse"> <div class="navbar-header"> <span class="navbar-brand">FAR BACKOFFICE</span> </div> <ul class="nav nav-pills"> @foreach (var node in Model.Nodes) { if...

Add XElement dynamically using loop in MVC 4?


c#,xml,asp.net-mvc-4,for-loop
i will like to add the Xelement in Xdocument but how can i add in dynamically using loop? I need to capture the user multiple answer and generate the Xelement dynamically. Please guide me or provide any hint. Thanks alot! [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) {...

How do I properly send __RequestVerificationToken with an ajax request in MVC5


ajax,asp.net-mvc,asp.net-mvc-5
I'm trying to send an ASP.NET AJAX request to my application. In the application's controller, I have: [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Instructions,Glass,Notes")] Drink drink, [Bind(Include= "ID,Amount,Brand,IngredientID,DrinkID")] IEnumerable<DrinkIngredient> DrinkIngredients) { if (ModelState.IsValid) { //and so on my javascript looks like this: console.log($('#editDrinkForm').serialize()) var x = new XMLHttpRequest(); x...

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...

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...

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,...

Convert string value to english word


c#,asp.net-mvc-5
I'm trying to figure out / where to start in regards to this situation say for example I enter $127.45 in to a textbox I would expect the application to spit back one hundred and twenty-seven dollars and forty-five cents The word will then be placed on a document and...

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...

Getting users from another AD Domain using PrincipalContext


c#,asp.net,active-directory,asp.net-mvc-5,active-directory-group
How would I get users from an AD Group which contains users from different domains. For example, I have 2 domains in my active directory, Domain1.corp.com and Domain2.corp.com I have an AD group called TestGroup which contains users from both the domains. Domain1 users: TestUser1, TestUser2 Domain2 users: TestUser3, TestUser4,...

Use Bearer Token Authentication for API and OpenId authentication for MVC on the same application project


c#,asp.net-mvc-4,oauth-2.0,openid,identityserver3
I am trying to use both OpenId and Bearer token authentication on my application through Identity Server. The problem currently is that once I have authenticated the user, I still need to get a bearer token to be able to call any action methods for my Asp.Net MVC application. Here...

Why mozilla changes the characters when i use the .net mvc statement redirect?


c#,asp.net-mvc-4,redirect,mozilla
I'm trying to redirect to an external website when everything is done, but firefox changes the http word on the url for a weird set of characters. This is my server side code: [HttpPost] public ActionResult Postular(INFO_BASE_POSTULACION_model pInfoPostulacion) { string rutMD5 = Request["rutMD5"]; int idRegion = Convert.ToInt32(Request["idRegion"]); int idInstrumento =...

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 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...

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...

Angularjs ng-show doesn't work with Viewbag


angularjs,asp.net-mvc-4
In Angularjs template is it possible to use ViewBag.Property in ng-show? I set some viewbag in my controller/action like this ViewBag.AllowExport = false; when i tried following nothing happen <div ng-show="@ViewBag.AllowExport"> <a href="JavaScript:void(0);">Export</a> </div> Above Div is still showing even if AllowExport = false; Is my syntax is wrong here...

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 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...

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 {@class = "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...

Need to Close the div in if condition MVC View


asp.net-mvc,asp.net-mvc-4
I am trying to close a div inside the if condition which is inside a foreach loop. @foreach (var item in ViewBag.modal) { counter++; <div class="Class1"> <div class="span6"> <!-- block --> <div class="block"> <div class="block-header"> <div class="left"> @item["Topic"];</div> </div> <div class="collapsein"> @item["Desc"];</div> </div> </div> @if (counter % 2 == 0)...