asp.net-mvc,asp.net-mvc-4,ienumerable , Display List return from a controller to a table in view ASP.NET MVC4


Display List return from a controller to a table in view ASP.NET MVC4

Question:

Tag: asp.net-mvc,asp.net-mvc-4,ienumerable

I have a function in my controller class, it return a list of data, i want to display it in table structure in my view page. i had tried the following code but it shows some error

"Class does not contain definition of GetEnumerator"

Controller

public ActionResult data(Message msg,IEnumerable<sample> dept)
{
    dbconnection db = new dbconnection();
    sample s = new sample();
    SqlConnection con = new SqlConnection(db.GetconString());
    DataTable dt;   
    List<examplemvc1.Models.sample> datatable = new List<sample>();
    dt = db.BuildDT("select * from MVCsample");
    foreach (DataRow row in dt.Rows)
    {
        s.FirstName = Convert.ToString(row["First Name"]);
        s.LastName = Convert.ToString(row["Last Name"]);
        s.Address = Convert.ToString(row["Address"]);
        s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
        s.Location = Convert.ToString(row["Location"]);
        datatable.Add(s);
        dept = datatable;  
    }
    ViewBag.tabledata = dept;
    return View(dept) ;
}

Model

public class sample
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
    public string Location { get; set; }
    public string tabledata { get; set; }
}

public class Message
{
    public IEnumerable<sample> sampleList { get; set; }
    public string MessageText { get; set; }
    public string MessageFrom { get; set; }
}

View

@model examplemvc1.Models.sample

@foreach (var data in Model)
{
    <table><tr><td>@data.FirstName</td></tr></table>
}

UPDATE this is how my entire view looks like

@model List<examplemvc1.Models.sample>
@{
    ViewBag.Title = "Registration Form";
}
<head>
    <script type="text/javascript" src="../../Scripts/jquery-1.7.1.min.js"></script>
    <link href="../../Style/sample.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/samplescript.js" type="text/javascript"></script>
</head>
<h2>
    Registration Form </h2>
   <body>

  <table>
 <tr>
 <th>
   First Name
 </th>
 </tr>

@foreach (var data in Model)
{
    <tr><td>@data.FirstName</td></tr>
}
</table>



@using (Html.BeginForm())
{

    <table id="table1">
    <tr>
         <td> 

             @Html.Label("Enter FirstName", new { @class = "standard_label_style" })
        </td>
         <td>
             @Html.TextBoxFor(a => a.FirstName, new { @class = "class1", title = "Enter FirstName", id = "NameBox", placeholder = "Enter name", onkeydown = "return TextField(event)" })
          <span class="errorMessage"></span>
           @if (!ViewData.ModelState.IsValid)
           {       
                <span class="field-validation-error">
                @ViewData.ModelState["FirstName"].Errors[0].ErrorMessage</span>
           }     
    </td>
    </tr>


    <tr>
    <td>
    @Html.Label("Enter LastName", new { @class = "standard_label_style" })
    </td>
    <td>

    @Html.TextBoxFor(a => a.LastName, new { @class = "class1", placeholder = "Enter name", id = "LastNameBox", title = "Enter Lastname", onkeydown = "return TextField(event); " })
        <span class="errorMessage"></span>
       </td>
    </tr>
    <tr>
    <td>
     @Html.Label("Enter Address", new { @class = "standard_label_style" })
     </td>
     <td>
      @Html.TextBoxFor(a => a.Address, new { @class = "class1", id = "AddressBox", placeholder = "Enter name", title = "Enter Address" })
    <span class="errorMessage"></span>
   </td>
    </tr>
    <tr>
   <td>
    @Html.Label("Enter PhoneNumber", new { @class = "standard_label_style" })
    </td>
    <td>
    @Html.TextBoxFor(a => a.PhoneNumber, new { @class = "class1", id = "PhoneBox", placeholder = "Enter name", title = "Enter Phonenumber", onkeydown = "return ValidateNumber(event);" })
    <span class="errorMessage"></span>
    </td>
  </tr>
  <tr>
  <td>
    @Html.Label("Enter Location", new { @class = "standard_label_style" })
    </td><td>
      @Html.TextBoxFor(a => a.Location, new { @class = "class1", id = "LocationBox", placeholder = "Enter name", title = "Enter Location" })
      <span class="errorMessage"></span>
      </td>
     </tr>
   </table>
    <input type="button" id="btnSave"  value="Register"/>
     <input type="button" value="Clear"/>
     <input type="button" id="Tabledata" value="Tabledata"/>
    <div id="div1"></div>

   @*@Html.ValidationSummary()*@








   <script type="text/javascript">

       function ValidateNumber(e) {
           var evt = (e) ? e : window.event;
           var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
           if (charCode > 31 && (charCode < 48 || charCode > 57)) {
               return false;
           }
           return true;
       };
       function TextField(e) {
           var evt = (e) ? e : window.event;
           var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
           if (charCode > 31 && (charCode < 48 || charCode > 56)) {
               return true;
           }
           else if (charCode == 8 || charCode == 9) {
               return true;
           }
           return false

       };


   </script>

}
   </body>

Error is shown in my view code, actually I don't know how to get that values in view page. I am newbie in mvc. Please help me to solve this. Any help will be greatly appreciated.

"Update"

I had solved My problem with the help of Stackoverflow Below is my correctcode

Controller

 public ActionResult data()
        {
            SomeViewModel model = new SomeViewModel();
            dbconnection db = new dbconnection();
            SqlConnection con = new SqlConnection(db.GetconString());
            DataTable dt = db.BuildDT("select * from MVCsample");
            foreach (DataRow row in dt.Rows)
            {
                sample s = new sample();
                s.FirstName = Convert.ToString(row["First Name"]);
                s.LastName = Convert.ToString(row["Last Name"]);
                s.Address = Convert.ToString(row["Address"]);
                s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
                s.Location = Convert.ToString(row["Location"]);
                model.samples.Add(s);
            }
            return View(model);
        }

Model

namespace examplemvc1.Models
{
    public class sample
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Address { get; set; }


        public string PhoneNumber { get; set; }

        public string Location { get; set; }
         public string tabledata { get; set; }

    }
    public class Message
    {
        public IEnumerable<sample> sampleList { get; set; }
        public string MessageText { get; set; }
        public string MessageFrom { get; set; }
    }
    public class SomeViewModel
    {
        public SomeViewModel()
        {
            samples = new List<sample>();
            sample = new sample();
        }
        public List<sample> samples { get; set; }
        public sample sample { get; set; }
    }
}

view

@model examplemvc1.Models.SomeViewModel

//................

@foreach (var data in Model.samples)
{
    <tr><td>@data.FirstName</td>
     <td>@data.LastName</td>
     <td>@data.Address</td>
     <td>@data.PhoneNumber</td>
     <td>@data.Location</td></tr>
}
</table>

Just look at Stephen Muecke's Answer below he has explain the context very clearly


Answer:

You view is displaying both a list of sample and what appears t be a form for a new sample. Start by creating a view model to represent what you want to display/edit

public class SampleVM
{
  public SampleVM
  {
      SampleCollection = new List<sample>
  }
  public List<sample> SampleCollection { get; set; }
  public sample NewSample { get; set; }
}

In your controller modify the code to

public ActionResult data()
{
    SampleVM model = new SampleVM();
    dbconnection db = new dbconnection();
    SqlConnection con = new SqlConnection(db.GetconString());
    DataTable dt = db.BuildDT("select * from MVCsample");
    foreach (DataRow row in dt.Rows)
    {
        sample s = new sample();
        s.FirstName = Convert.ToString(row["First Name"]);
        s.LastName = Convert.ToString(row["Last Name"]);
        s.Address = Convert.ToString(row["Address"]);
        s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
        s.Location = Convert.ToString(row["Location"]);
        model.SampleCollection.Add(s);
    }
    return View(model);
}

Notes:

  1. Remove the parameters from the GET method. Apart from the fact you don't use them so they are pointless, even if you were to try and pass those objects to the method, binding would fail and the collections would be null (and if you were to construct the correct query string to make it work, it would be so long it would almost certainly throw an exception)
  2. You need to initialize a new sample inside the foreach loop (your code only initialized one object, and each loop updated its properties to the current row, so you would end up with multiple reference of the same object, all matching the values of the last row in your table)
  3. There is no need to pass the model as a ViewBag property (its already passed to the view using return View(model);

And modify your view to

@model SampleVM
....
<table>
    @foreach(var sample in Model.SampleCollection)
        <tr>
            <td>@sample .FirstName</td>
        </tr>
    }
</table>
@Html.BeginForm())
{
  @Html.LabelFor(m => m.NewSample.FirstName, "Enter FirstName", new { @class = "standard_label_style" })
  @Html.TextBoxFor(m => m.NewSample.FirstName, @class = "class1", placeholder = "Enter name", title = "Enter Lastname")
  @Html.ValidationMessageFor(m => m.NewSample.FirstName)
}
....
<input type="submit" id="btnSave"  value="Register"/>

Notes:

  1. A label element if for associating the element with a control. Your usage generates <label for="Enter_FirstName"> but you dont have a control with id="Enter_FirstName". Preferable you should have [Display(Name = "Enter FirstName")] on the property, but otherwise use the strongly types helper
  2. Use @Html.ValidationMessageFor() to render ModelState errors, although in your case all you properties are strings and you don't have any validation attributes so there will never be any errors, so its a bit pointless
  3. The html helpers generate an id attribute. There is rarely a need to overwrite it. Stop polluting your markup with behavior and learn to use Unobtrusive Javascript
  4. Your form did not contain a submit button

Related:


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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[] {...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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