I have a web application being developped on Windows 8.1, .net 4.5.1, IIS 8.5 (under Integrated AppPool), Visual Studio 2013 Over the default template that includes asp.net Identity, Owin, etc. and locally works fine.

then I Uploaded it to a windows server 2008 & IIS 7.5 (Integrated Pipeline) Host and I get:

This operation requires IIS integrated pipeline mode.

Exception Details: System.PlatformNotSupportedException: This operation requires IIS integrated pipeline mode.

Stack Trace:

[PlatformNotSupportedException: This operation requires IIS integrated pipeline mode.]
System.Web.HttpResponse.get_Headers() +9687046
System.Web.HttpResponseWrapper.get_Headers() +9
Microsoft.Owin.Host.SystemWeb.OwinCallContext.CreateEnvironment() +309
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.GetInitialEnvironment(HttpApplication application) +246
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.PrepareInitialContext(HttpApplication application) +15
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.BeginEvent(Object sender, EventArgs e, AsyncCallback cb, Object extradata) +265
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +285
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

I have searched a lot and unable to find anything except for directing the reader to change the pipeline from classic mode to integrated mode that which I already did with no luck..

What can I do to fix the problem? Does "Microsoft.Owin.Host.SystemWeb" not like IIS 7.5, or server 2008 or me :) ?

I'd like to upload images from an uri postet to an asp.net mvc5 controller to azure blob storage. I already got it working with HttpPostedFileBase, like this. Can I somehow get the memory stream from an image uri?

HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
var imgFile = System.Drawing.Image.FromStream(hpf.InputStream, true, true);
CloudBlockBlob blob = coversContainer.GetBlockBlobReference("img.jpg");
MemoryStream stream = new MemoryStream();
imgFile.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
blob.UploadFromStream(stream);

  • How can I get the id of the currently logged in user in MVC 5? I tried the StackOverflow suggestions, but they seem to be not for MVC 5.
  • Also, what is the MVC 5 best practice of assigning stuff to the users? (e.g. a User should have Items. Should I store the User's Id in Item? Can I extend the User class with an List<Item> navigation property?

I'm using "Individual User Accounts" from the MVC template.

Tried these:

'Membership.GetUser()' is null.

I run the Web Application HomeController.Index() action is run. Then I go to Person.Index()(it is at the bottom of this post) via browser then and only then Migrations.Configuration.Seed() is invoked. But I want it to happen at the application start.

Configuration:

namespace WebApplication2.Migrations {
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using WebApplication2.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.ApplicationDbContext> {
        public Configuration() {
            AutomaticMigrationsEnabled = true;
            ContextKey = "WebApplication2.Models.ApplicationDbContext";
        }

        protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {

            System.Diagnostics.Debug.WriteLine("Seed started");
            //  System.Data.Entity.DropCreateDatabaseAlways<ApplicationDbContext> s = new DropCreateDatabaseAlways<ApplicationDbContext>();
            // s.InitializeDatabase(context);
            if (!context.Persons.Any()) {
                var persons = new List<Person> { 
             new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "312312312", Notes = "Annoying"},
             new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "113-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "548555672", Notes = "Less Annoying"}
            };

                persons.ForEach(person => context.Persons.AddOrUpdate(person));
                context.SaveChanges();
            }

            if (!context.Meetings.Any()) {
                var meetings = new List<Meeting>{
                new Meeting{PersonId = 1, Body = "Body of meeting", Date = DateTime.Now}
            };


                meetings.ForEach(meeting => context.Meetings.AddOrUpdate(meeting));
                context.SaveChanges();
            }
            if (!context.Statuses.Any()) {
                var statuses = new List<Status> {
                new Status{Name = "OK"},
                new Status {Name = "NOT_OK"}
            };



                statuses.ForEach(status => context.Statuses.AddOrUpdate(status));
                context.SaveChanges();

            }
            //Users Seeding

            if (!context.Users.Any()) {
                System.Diagnostics.Debug.WriteLine("USER SEED");
                try {
                    var store = new UserStore<ApplicationUser>(context);
                    var manager = new UserManager<ApplicationUser>(store);
                    //why user is not created
                    var user1 = new ApplicationUser { UserName = "admin", Email = "informatyka4444@wp.pl" };
                    var user2 = new ApplicationUser { UserName = "emp", Email = "informatyka4444@wp.pl" };
                    manager.Create(user1, "admin");
                    manager.Create(user2, "emp");

                    context.SaveChanges();
                } catch (Exception e) { System.Diagnostics.Debug.WriteLine("THERE WAS AN EXCEPTION"); }
            }


        }
    }
}

IdentityModels.cs

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace WebApplication2.Models {
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false) {
            System.Diagnostics.Debug.WriteLine("CONSTRCTOR");
          // Database.SetInitializer(new DropCreateDatabaseAlways<ApplicationDbContext>());
        }



        public DbSet<Person> Persons { get; set; }
        public DbSet<Meeting> Meetings { get; set; }
        public DbSet<Status> Statuses { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public static ApplicationDbContext Create() {
            return new ApplicationDbContext();
        }
    }
}

Global.asax:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication2.Migrations;
using WebApplication2.Models;


namespace WebApplication2 {
    public class MvcApplication : System.Web.HttpApplication {
        protected void Application_Start() {
            System.Diagnostics.Debug.WriteLine("Application_Start");
            Database.SetInitializer(new DropCreateDatabaseAlways<ApplicationDbContext>());
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }

}

Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication2-20140711041006.mdf;Initial Catalog=aspnet-WebApplication2-20140711041006;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
   <!-- <contexts>
     <context type="WebApplication2.Models.ApplicationDbContext, WebApplication2">
        <databaseInitializer type="WebApplication2.Migrations.Configuration, WebApplication2" />
      </context>
    </contexts>-->
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

The Person controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Models;

namespace WebApplication2.Controllers {
    public class PersonController : Controller {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Person
        public ActionResult Index() {
            return View(db.Persons.ToList());
        }

        // GET: Person/Details/5
        public ActionResult Details(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Person person = db.Persons.Find(id);
            if (person == null) {
                return HttpNotFound();
            }
            return View(person);
        }

        // GET: Person/Create
        public ActionResult Create() {
            return View();
        }

        // POST: Person/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FirstName,LastName,CellNumber,SecondaryPhoneNumber,Address,BirthDate,Pesel,Notes")] Person person) {
            if (ModelState.IsValid) {
                db.Persons.Add(person);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(person);
        }

        // GET: Person/Edit/5
        public ActionResult Edit(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Person person = db.Persons.Find(id);
            if (person == null) {
                return HttpNotFound();
            }
            //Moj kod
            //Album album = db.Albums.Find(id);
            //ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
            //ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
            ViewBag.StatusId = new SelectList(db.Statuses, "Id", "Name", person.StatusId);



            //Moj kod
            return View(person);
        }

        // POST: Person/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,CellNumber,SecondaryPhoneNumber,Address,BirthDate,Pesel,Notes,StatusId")] Person person) {
            if (ModelState.IsValid) {
                db.Entry(person).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(person);
        }

        // GET: Person/Delete/5
        public ActionResult Delete(int? id) {
            if (id == null) {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Person person = db.Persons.Find(id);
            if (person == null) {
                return HttpNotFound();
            }
            return View(person);
        }

        // POST: Person/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id) {
            Person person = db.Persons.Find(id);
            db.Persons.Remove(person);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing) {
            if (disposing) {
                db.Dispose();
            }
            base.Dispose(disposing);
        }


        public string formatPhoneNumber(string number) {
            Regex rgx = new Regex("[^0-9]");
            return rgx.Replace(number, "");
        }

        public ActionResult Call(int id, string number) {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            string formattedNumber = "tel:+48" + formatPhoneNumber(number);
            System.Diagnostics.Debug.WriteLine("NUMBER " + formattedNumber);
            proc.StartInfo.FileName = formattedNumber;
            proc.Start();
            Person person = db.Persons.Find(id);
            return RedirectToAction("Edit", new Person { Id = id });
        }
    }
}

I have an asp.net page with a TreeView that is bound to a SiteMapDataSource object.

What I would like to do is each time a user selects an item in the TreeView, automatically collapse all other branches that are not part of the selected item. I have spent the last day searching for possible solutions and am starting from scratch because either (a) it caused an "infinite loop" error or (b) it simply didn't do what I needed it to do.

Any help would be appreciated.

Here is the code showing the relevant objects:

<asp:SiteMapDataSource ID="smdsProdcutsMenu" runat="server" StartingNodeUrl="~/Products/products.aspx" />
<asp:TreeView ID="tvCategory" runat="server" CssClass="Treeview" NodeWrap="true" DataSourceID="smdsProdcutsMenu" ShowLines="True" ontreenodeexpanded="TreeNodeExpanded">
<SelectedNodeStyle BackColor="White" Font-Bold="True" ForeColor="Blue" />
</asp:TreeView>

Through testing, I have seen that the only event triggered by clicking on an item in the Treeview is TreeNodeExpanded.

The scriptblock is empty now because I am starting from square one and do not know what to put here. Here is where I need help.

<script runat="server">    
Protected Sub TreeNodeExpanded(sender As Object, e As System.Web.UI.WebControls.TreeNodeEventArgs)
' (1) what item was just clicked?
' (2) Collapse everything not contained in the branch of the selected item.
End Sub
</script>

Thank you for any help.

I'm trying to add scroll bars in both x and y but I only can add y-scroll. At the moment, my gridview is showing only partial data, it is missing 3-4 columns so I really need to use x-scroll. I've tried "overflow-x: scroll;" but it doesn't work.

My source code

<div style= "overflow-x:scroll; Overflow:scroll; max-height: 150px; width: 800px">
                                                    <asp:GridView ID="GridViewUpBus" runat="server" AutoGenerateColumns="False" Font-Names="Arial" Font-Size="Small" HorizontalAlign="Center">
                                                        <Columns>
                                                            <asp:BoundField DataField="SubCatID" HeaderText="Sub category ID">
                                                            <ItemStyle Width="10%" />
                                                            </asp:BoundField>

If I run, it looks like this. 2 more columns are not showing enter image description here

Could it be achieved by not using javascript? If I need to use "jquery-1.4.1.js" or "gridviewScroll.min.js" where can I download it? Sorry I'm pretty new to programming and I don't really know how to use javascript or jquery. It'd be great if I could add boarder lines in the gridview. Thanks in advance!

my database column name is "from" but am getting error while i change the column name to other name error is not occuring.why?

    protected void Button1_Click(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
    con.Open();
    string qry="insert into Mynew(name,age,from,address,job)values(@name,@age,@from,@address,@job)";
    SqlCommand cmd= new SqlCommand(qry, con);
    cmd.Parameters.AddWithValue("@name", TextBox1.Text);
    cmd.Parameters.AddWithValue("@age", TextBox2.Text);
    cmd.Parameters.AddWithValue("@from",TextBox3.Text);
    cmd.Parameters.AddWithValue("@address", TextBox4.Text);
    cmd.Parameters.AddWithValue("@job", TextBox5.Text);
    cmd.ExecuteNonQuery();
    con.Close();
    }

when i change column name to city am not getting error why is it happening?

Whenever I use the @ sign with a Razor page, such as this:

<script type="text/javascript">
if( @(ProjectName.NameSpace.booleanVariable) ) {
    doStuff();
}
</script>

then I get syntax error notifications all over the place that turn out fine after the conversion to HTML:

<script type="text/javascript">
if(True) {
    doStuff();
}
</script>

This is just a simple example but it occurs in other places as well. I will cite other examples if they become necessary. I couldn't find an answer among other stackoverflow questions, but with such a basic question I assume one is around. Links to said question are encouraged.

edit: Realized I should show that examples are JS inside Razor Page.

Question Is: How do I prevent these syntax error notifications so that I can identify and manage real syntax errors easily.

I am trying to take a 10 digit phone number (1234567890) that is returned from the database and format it to render on the view page as (123) 546-7890.

Is the best way to do that coming from the database to the view, or to take the 10 digits from the user and format it going into the database?

Thanks for responding to the newb question.

What is the possibly security issues with SharePoint as internet website? What is the possible problem? like _layouts, web services ect? Which thing Should I secure in my environment?

I am trying to use MVCJQGrid in my project.

I have a date column as below.

.AddColumn(new Column("RequiredDate").SetFormatter(Formatters.Date).SetSearchType(Searchtype.Datepicker).

SetSearchDateFormat("dd-mm-yy").SetSearchOption(SearchOptions.Less))

Problem: In the above snippet, the code I have written searches for data with entities which have a "RequiredDate" less then selected date. But, I would like to have a selection for comparison operator like "greater than", "less than", "equal to".

Can some one please share your opinions as I am trying to use the column filters ?

Thanks in Advance.

Regards, Sam

Is there a way to use viewmodel variable as a name of the resource? Like so, @Resources.(@Model.Apples) or similar?

The reason why I can't get away by only using resources is that content isn't static - it's loaded from database. And the reason number two is that I ALSO want to group it by their names and it's not currently possible since the names are in different languages.

I hope you get the grasp, but here's the example.(Simplified)

    Apples                   6
    Pommes                   19  

    Total                    25

This is what i get. But here's what I need to get: (If English locale)

    Apples                   25  

    Total                    25

So the overall problem is - I know how to localize static content, but the dynamic is a trouble, especially if I try to group it.

Thanks.

P.S. Or maybe at least someone knows how to concatenate the resource string in the controller? Like so -

var subj = "Difuse";
var TehString = Resources.Resources + subj;

Kendo UI edit option showing some unexpected behaviour, as you can see in the image there is a text box below Server column and 2 below ServerIP column all containing the id of server "SQL" i selected. Problem is when ever i want to show Server IP column this behaviour occurs, both server and server IP are from the same table.

Overlapping Fields in Edit Option

@(Html.Kendo().Grid<EnvironmentPOCO>()
      .Name("Grid")
      .Columns(columns =>
      {
          columns.Bound(d => d.EnvironmentName).Width(200).Title("EnvirontmentName");

          columns.ForeignKey(d => d.EnvironmentTypeID, (List<EnvironmentTypePOCO>)ViewData["EnvironmentType"], "EnvironmentTypeID", "EnvironmentTypeCode").Width(150).Title("EnvironmentCode").EditorTemplateName("_EnvironmentCodeDropDown");
          columns.ForeignKey(d => d.ServerID, (List<ServerPOCO>)ViewData["ServerDetails"], "ServerID", "ServerName").Width(200).Title("Server").EditorTemplateName("_ServerDropDown");
          columns.ForeignKey(d => d.ServerID, (List<ServerPOCO>)ViewData["ServerDetails"], "ServerID", "ServerIP").Width(200).Title("ServerIP");
          columns.ForeignKey(d => d.ProjectID, (List<ProjectPOCO>)ViewData["Projects"], "ProjectID", "ProjectName").Width(200).Title("ProjectName").EditorTemplateName("_ProjectNameDropDown");
       //   columns.ForeignKey(d => d.ProjectID, (List<ProjectPOCO>)ViewData["Projects"], "ProjectID", "ProjectDescription").Width(200).Title("ProjectDescription")/*.EditorTemplateName("_ProjectDescription")*/;

          columns.Command(d =>
          {
              d.Edit();
              d.Destroy();

          }).Width(200).Title("Action");
      })
      .ToolBar(tools => tools.Create())
      .Sortable()
      .Pageable()
      .Filterable()
      .DataSource(dataSource => dataSource
        .Ajax()
            .Model(model =>
                {
                    model.Id(m => m.EnvironmentID);
                    model.Field(m => m.EnvironmentName);
                    model.Field(m => m.EnvironmentTypeID);
                    model.Field(m => m.ProjectID);
                    model.Field(m => m.ServerID);

                })
            .Read(read => read.Url(ViewBag.ApiBaseUrl).Type(HttpVerbs.Get))
            .Create(create => create.Url(ViewBag.ApiBaseUrl).Type(HttpVerbs.Post))
            .Update(update => update.Url(ViewBag.ApiBaseUrl).Type(HttpVerbs.Put))
            .Destroy(destroy => destroy.Url(ViewBag.ApiBaseUrl).Type(HttpVerbs.Delete))
      )
)

This question already has an answer here:

Hello StackOverflow members,

I have two controllers:

public class FirstController : Controller
{
    public string Index()
    {
        return "FirstController - Index";
    }
}

public class SecondController : Controller
{
    public string Index()
    {
        return "SecondController - " + language;
    }
}

And I have two URLs: 1. mysite.com/ 2. en.mysite.com/

I expect to get:

  1. FirstController - Index

  2. SecondController - en

where en can be any param.

How should I adjust my Global.asax to fix this issue:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }

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

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

I have made a cascading drop downlist shown in the image below, following the example of KendoUI Cascading DropDownlist ASP.NET MVC(cs.html)

enter image description here

Database Relationship of servers and logins are many to many, so what i have done until now is when i click on a server it show's me all the passwords related to it. What i want now is when i click on a login it should update servers dropdown list and show me all the servers attached to that login, i would really appreciate the suggestions.

I'm trying to make a review section, but I only want it to show if there's 3 or more reviews posted.

When I do this I just seem to get an error.

@{
  var reviewCount = db.Query("SELECT COUNT(DISTINCT ID) FROM Reviews");
}

@if (reviewCount >= 3)
{
    <section class="col-md-12 reviews">
        <h2>Anmeldelser</h2>
        @foreach (var row in db.Query("SELECT TOP 3 * FROM Reviews ORDER BY DateTime"))
        {
            <article class="col-md-4">
                <p>" @row.Text "</p> <p>- @row.FirstName @row.LastName</p>
            </article>
        }
    </section>
}

I am new to code.Anyone out there to help .

How can i implement wall post like this.

When user update the status it have to post side by side.

![enter image description here][1]

http://upload.wikimedia.org/wikipedia/en/3/38/Google%2B_interface.png

I'm spent too much time trying to figure this out. I've not been able to work it out on my own. The following method is in my custom IView. It reads the contents of my views and returns an IView. The problem is that it won't render the razor code within the view.

    public void Render(ViewContext viewContext, System.IO.TextWriter writer)
    {
        //Load File
        var rawContents = File.ReadAllText(this.viewPhysicalPath);

        // Able to modify rawContents but Razor code isn't not being rendered.

        writer.Write(parsedcontents);
    }

This method below is part of my CustomRazorViewEngine. If have I had the implementation of base.CreateView I would think that would be where the file is read in and would be a perfect place to solve my problem. I have no idea how to find the source.

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var view = base.CreateView(controllerContext, viewPath, masterPath);

        return view;
    }
  1. I want to read in the cshtml file for the current view. Ultimately I would like to read the cshtml file from a database source.
  2. I would like to be able to change the contents of the view. I do not have to have this feature but it would be a really nice option if I needed to dynamically change content.
  3. I want the razor code to be executed. <- This is my real problem. I can read in a cshtml file using a custom IView but doing so apparently cripples my ability to render the razor code in the page.

If anyone can help, this would be really helpful to me for work. I've been able to implement several of the options I want but when I try to combine them into a single solution I can't get it to work.

Back Story:

Where I work if we need to make a change, even a small change it requires that we create an RFC (Request for Change). Except in emergency conditions, it usually takes from 1 week to a month to get a release. On the other hand we can make database changes with in a couple of hours. I was thinking how nice it would be if I could write a process that you copy all the cshtml files into our database once after each release. That doesn't seem like it would be too difficult. I figured out how to create a custom IView that read the contents of the cshtml files. It doesn't seem to be much of a stretch to read the views in from a database instead of a file. My problem is that when I read in a cshtml file it doesn't render the razor code. Instead it's displaying the raw razor source.

My work so far has been to create a CustomViewEngine class that inherits from VirtualPathProviderViewEngine that calls my customView which successfully reads the contents of the cshtml file. If I register the engine then I get the contents displayed in the view but the razor source code is displayed on in the view.

I also created a CustomRazorViewEngine by inheriting RazorViewEngine. This works very nice and renders the razor code and I was able to limit the engine to searching for .cshtml files only which is a nice bonus but I have not found a way of pulling the view content from a data source in this class.

I've explored the inheritance tree for the view engine trying to find a better place to inject my custom code but I'm lost.

VirtualPathProviderViewEngine -> BuildManagerViewEngine -> RazorViewEngine -> IViewEngine

I have code examples of my two classes but they are fairly standard. Similar classes are available all over stackoverflow and other places.

I am new to asp.net and frontend technologies in general. I have the following code:

<ul>
    @foreach (var item in Model)
    {
        <li>
            <img src="@item" alt="file here" width="100" height="100" />
            <a id="@item" href="#" onclick="deleteFile('@item');">Delete</a>
        </li>
    }
</ul>

<script>
    function deleteFile(item) {
        var url = "/Home/DeleteFile";
        $.post(url, { Name: item }, function (data) {
            window.location.href = "/Home/Upload";
        });
    }
</script>

I know we can recognize the language in which the script is written by the type tag. E.g.

<script type="text/javascript"...

But without this type specified, how can I recognize the language of the script? Further in the script, what is the argument "function(data)" in the post statement doing and where is the data argument for that function coming from?

Thanks!

I have Cascading DropDownLists (Kendo UI), I want to add them into the KendoUI Grid, because i want to add a search option to each list, so that user can find data through it easily, below is the code, how can i achive it.

@using List.Model.Model
@{
    ViewBag.Title = "Servers";
}


<

    h2>@ViewBag.Title</h2>
     @(Html.Kendo().DropDownList()
                  .Name("servers")
                  .OptionLabel("Select Server...")
                  .DataTextField("ServerName")
                  .DataValueField("ServerID")
                  .DataSource(source => {
                       source.Read(read => {
                           read.Action("GetCascadeServers","ServerLogins") 
                           .Type(HttpVerbs.Get);
                       });
                  })
            )


    @(Html.Kendo().DropDownList()
                  .Name("Logins")
                  .OptionLabel("Select Login...")
                  .DataTextField("passwd")
                  .DataValueField("LoginID")
                  .DataSource(source => {
                      source.Read(read =>
                      {
                          read.Action("GetCascadeLogins", "ServerLogins")

                              .Data("filterLogins")
                              .Type(HttpVerbs.Post);

                      })
                      .ServerFiltering(true);
                  })
                  .Enable(false)
                  .AutoBind(false)
                  .CascadeFrom("servers")
            )
    <script>
                function filterLogins() {
                    return {
                        servers: $("#servers").val()
                    };
                }
    </script>

Referring to the original code here, which works perfectly.

In the LoadData.cshtml file, we find the following code:

var data = "";
foreach(var row in rows){
    data += "<tr><td>" + row.ProductID + "</td><td>" + row.ProductName + 
            "</td><td>" + row.UnitPrice + "</td></tr>";
}

It's working fine when the code is within a single loop:

foreach(var row in rows){
    ... //some code here but no nested foreach loop or loop but only <td> or <tr>
}

However, I was thinking about a broader and more general nested function. What if we have a code like:

foreach{
    ... //some divs here
    foreach{
        ... //some divs here
        row.ProductID row.ProductName
    }
}

How can we implement the load on scroll function in case of such a case?

EDIT

I want to implement the following code:

                                                        @foreach(var rowfollow in getfollowingusernamedata){
                                                        following_username = rowfollow.student_username;
                                                        <div class="panel-body">
                                                            <div class="activity-stream">
                                                                @foreach(var statusrow in db.Query(selectstatuscommand, session_username, following_username)){
                                                                <div class="media">
                                                                    <a class="pull-left" href="profile.cshtml?username=@statusrow.status_username">
                                                                        <img class="media-object" src="@statusrow.status_avatar" alt="@statusrow.status_firstname @statusrow.status_lastname">
                                                                    </a>
                                                                    @if(statusrow.status_username.ToString() == session_username.ToString()){
                                                                        <a class="pull-right" id="modal-delete" href="#modal-container-@statusrow.status_id" role="button"data-toggle="modal"> Delete </a>
                                                                    }
                                                                    <div class="media-body">
                                                                        <h4 class="media-heading"><a href="profile.cshtml?username=@statusrow.status_username">@statusrow.status_firstname @statusrow.status_lastname</a></h4>
                                                                         <p>@statusrow.status_body</p>
                                                                        <img src="@statusrow.status_image" class="statusimage">
                                                                        <form class="form-comment" method="post" action="" id="commentform">
                                                                            <div class="form-group">
                                                                                <input type="text" class="form-control" placeholder="Write a comment ..." name="commentbody">
                                                                                <input type="hidden" class="form-control" value="@statusrow.status_id" name="commentstatusid" style="display: none;">
                                                                                <button type="submit" class="btn btn-primary" value="sharecomment" name="button" style="display: none;">Submit</button>
                                                                            </div>
                                                                        </form>
                                                                        @foreach(var commentrow in db.Query(getcommentcommand, @statusrow.status_id)){
                                                                        <div class="media">
                                                                            @foreach(var getuserId in db.Query("SELECT student_firstname, student_lastname, student_avatar, student_username from student where student_id = @0", @commentrow.comment_userid)){
                                                                            <a class="pull-left" href="profile.cshtml?username=@getuserId.student_username">
                                                                                <img class="media-object" src="@getuserId.student_avatar" alt="Sarah Cole">
                                                                            </a>
                                                                            <div class="media-body">
                                                                                <h4 class="media-heading"><a href="profile.cshtml?username=@getuserId.student_username">@getuserId.student_firstname @getuserId.student_lastname</a></h4>
                                                                                <p>@commentrow.comment_body</p>
                                                                                <ul class="list-inline">
                                                                                    <!--<li><a href="#" class="small"><i class="fa fa-thumbs-o-up"></i> Like</a></li>
                                                                                    <li><a href="#" class="small">Comment</a></li>
                                                                                    <li><a href="#" class="small">Share</a></li>-->
                                                                                    <li><span class="muted small"><i class="imoon imoon-alarm fa-fw"></i> @commentrow.comment_time</span></li>
                                                                                </ul>
                                                                            </div>
                                                                            }
                                                                        </div>
                                                                         } 
                                                                    </div>
                                                                </div>
                                                                } 
                                                            </div>
                                                        </div>

                                                        }