FAQ Database Discussion Community


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

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

Javascript Object negative number

javascript,asp.net-mvc,razor
Create object adjustementType inside script tag in MVC 5 partial view. <script type="text/javascript"> var adjustementType = { -1:'Rate Decrease', 1: 'Rate Increase' }; </script> but getting following error "Expected identifier, string or number" . The error is thrown on area -1 & 1 field....

how to interpolate property names with razor

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

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

@Html.TextBoxFor not display a specific value

c#,asp.net,asp.net-mvc,razor,helper
I'm developing a website in ASP .Net with Razor. For my forms i'm using Helpers (like @Html.TextBoxFor) and i'd like NOT to show a specific value. It's tricky to explain, so here's some code. My model public class SearchedInstruction { private int _workCenterNumber= -1; public int WorkCenterNumber { get {...

ListBox that updates another part of View

c#,html,asp.net-mvc,razor,listbox
I want a ListBox, that when submitted, will send its selected values to a controller, and the response from that controller will be used to update a small piece of the view. The following code is able to update the part of the view, and get the selected values, but...

Disable Copy/Paste/Right Click in mvc TextBox

javascript,asp.net-mvc,razor
I have a textbox which accepts numeric value.This is handled using javascript. I'd like to disable copy, paste and right click functionalities for the text box. Any help would be appreciated. @Html.TextBoxFor(model => model.Days, new { @class = "input_box", @id = "txtDays", @onkeydown = "javascript:NumberOnly(this,event)"}) ...

Kendo Grid Date is null for 13/06/2015 all dates after 12

asp.net-mvc,razor,kendo-grid,kendo-asp.net-mvc
My grid: @(Html.Kendo().Grid<IBATechnologies.IBA.Web.Models.AssetTransactionDetailViewMod el>() .Name("transactionGrid") .Pageable() //.Editable(editable=>editable.Mode(GridEditMode.InLine)) .Columns(colums => { colums.Bound(p => p.assetCode).Width(100); colums.Bound(p => p.assetDesc).Width(100); colums.Bound(p => p.remark).Width(100); colums.Bound(p => p.currencyCode).Width(100); colums.Bound(p => p.rate).Width(100); colums.Bound(p => p.currencyRate).Width(100); colums.Bound(p =>...

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

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

NullReference Error while assiging values of Modeltype in MVC View (Razor)

vb.net,razor,model-view-controller,model
I have the following MVC Model: Public Class Employee Public Property EmployeeID As Integer End Class Controller: Namespace Controllers Public Class EmployeeController Inherits Controller Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View() End Function End Class End Namespace View: @ModelType MVCDemo.Employee...

C# 6 string interpolation in a Razor view? [closed]

c#,asp.net-mvc,razor,c#-6.0
Is this supported? If so, is there some trick to enabling it? I'm assuming Razor isn't using a new enough compiler...? The VS2015 IDE seems to be fine with it but at runtime I get a "CS1056: Unexpected character '$'".

In Javascript in a MVC Razor, replace a keyword with a value from the model

javascript,asp.net-mvc,razor
When you have some JavaScript on an MVC razor view is it possible to do a model variable replacement in the middle of a multipart statement. To clarify I have the code <script> function drawChart() { $.post('@Url.Content("~/Home/GetDataAssets")', function (d) { ... var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); }); };...

Take the first 100 characters from content MVC 5 ASP.NET

c#,asp.net,asp.net-mvc,razor
I am using asp MVC 5 with entity framework 6.1 code first. I made a view for the articles. I want to take only the first 100 characters from the content to put it in the index view. How can I do it ? <td> @Html.DisplayFor(modelItem => item.Content) </td> ...

Cannot access conditional Razor variable as href

c#,asp.net-mvc,razor
I have a razor view that generates a url based on some items returned by the model. When I create a url variable without any if statements, the url variable can be found and used as an href. However, when I have this code (using if statements) it says: "The...

Get Column title in View

asp.net-mvc,razor,parameters,title,actionlink
MVC5 did a great job on automatically creating the View page (Razor). It currently displays my list of Students for example with table heading like this: <th> @*@Html.ActionLink("", "Index", new { sortOrder = ViewBag.NameSortParm })*@ @Html.DisplayNameFor(model => model.LastName) </th> Now. DisplayNameFor take a Lambda Expression as its parameter. However, I...

Prefered way of building multi view layouts in ASP.NET MVC?

c#,asp.net,asp.net-mvc,angularjs,razor
I'm currently wondering about the prefered way to build multi view layouts using ASP.NET MVC. For example in angular-based SPAs, loading different views into a layout is pretty straightforward: <div ui-view="header"></div> <div ui-view="content"></div> .state("home", { views: { "header": { templateUrl: "app/_header.html" } ... However in MVC, there seem to be...

dynamic generation of CSS attributes in CSS files based on user input in ASP MVC

c#,css,asp.net-mvc,razor,themes
Most of the dynamic CSS Q & A show how to swap between CSS files or predefined CSS values. My question is: during a live user session how to compute/compile CSS values for e.g. both element.width2 and width:230px into the CSS file (element.width3 and width:430px;) before loading it to the...

404 Not Found Ajax jquery MVC

c#,jquery,ajax,asp.net-mvc,razor
I created an MVC3 project in Visual Studio 2013. The view engine is razor.First I write jquery.ajax in @section Scripts {} in view(cshtml) it works fine. But I seperate script in .js file and debugging I get error : (debugging IIS Express) IIS 8.0 Detailed Error - 404.0 - Not...

Http Post with duplicate name values MVC

c#,asp.net,asp.net-mvc,razor,http-post
In MVC I have a form that uses a lot of duplicate information. Basically they click a button and there is another "form"(text box drop down list etc) that pops up. When they click the submit button however all of that comes back with the same name. How would I...

Why HTML form empty field auto check disabled when false is returned from JS function on click of submit button? [duplicate]

javascript,jquery,html,forms,razor
This question already has an answer here: Triggering HTML5 Form Validation 4 answers If an HTML form contains an input text field and it is declared like this: <input type="email" id="loginEmail" placeholder="Email address" required> Then the if this field is empty and user clicks on submit button then an...

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

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

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

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

'System.Web.Mvc.SelectListItem' does not contain a property with the name 'id' #2

c#,asp.net,asp.net-mvc,entity-framework,razor
I have the following entities: public class Entidad { [Key] public int Id { get; set; } public string Nombre { get; set; } public virtual ICollection<Propiedad> Propiedades { get; set; } } public class Propiedad { [Key] public int Id { get; set; } public virtual Entidad Entidad {...

Get value off querystring by it's position

c#,asp.net,razor
I have a URL that's going to have one parameter on it but the 'name' of this parameter will, in some cases, be different eg. www.mysite.com/blog/?name=craig www.mysite.com/blog/?city=birmingham and what I'm trying to do is always get the value (craig / birmingham) of the first (and only) parameter on the string...

Can't get Editor Template to Work

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

Set var in foreach to use later

c#,razor
I'm trying to set a value in a foreach but i get the error that it dosent exist in the current contect. Here is my code; @{ string sUsr = System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToLower(); var db = Database.Open("SQLServerConnectionString"); var selectUser = "SELECT * FROM USERS WHERE username = " + @sUsr; } @foreach...

Razor foreach loop loses item property

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

MVC - Should I avoid to import more namespaces in view

asp.net-mvc,performance,razor,using-directives
I know some of you guys would consider it an unrelated question but, It's an important question for an MVC developer when you making it certain to make your application efficient and speedy. As you know that we can import a namespace into a view using 'using' clause. My question...

Render different tables in a view based on years

c#,asp.net-mvc,html5,razor
I am trying to make a view that renders different html tables for different years. The model used for the view is this: public class VisualizzaFattureViewModel { public FileInfo FatturaFile { get; set; } public int Year { get; set; } } And this is the controller action: public ActionResult...

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

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

MVC best practice for displaying static generated data

c#,asp.net-mvc,asp.net-mvc-4,razor
Question background: I have a two page MVC 4 web app. The first page's view currently has its data manually typed into the View as its static i.e nothing is being passed to the View from its associated Controller method, as shown: Index controller method: Public ActionResult Index() { return...

@Html.RadioButtonFor in mvc

c#,asp.net-mvc-4,razor
In my application, my model contains a field id, and in the view I need to select an id with a radio button and post back the selected id to the controller. How can I do this? My view is as follows, @model IList<User> @using (Html.BeginForm("SelectUser", "Users")) { <ul> @for(int...

Escaping quotes in Newtonsoft JSON

c#,asp.net-mvc,razor,json.net
I've an object: public class Test { public string Prop1 { get; set; } } I'd like to serialize it to json in a view, so in my cshtml: <script type="text/javascript"> var myJson = JSON.parse('@Html.Raw(JsonConvert.Serialize(Model.MyTest))'); </script> It works, until Prop1 contains quotes, because it gets rendered as: var myJson =...

ServiceStack View 403 (Forbidden)

razor,servicestack,servicestack-razor
I have setup Service Stack web project with a couple of views. I can access the /Default.cshtml view without any problems but when I try to access anything in the /Views/ folder I get the below error: Forbidden Request.HttpMethod: GET Request.PathInfo: /Views/MyView.cshtml Request.QueryString: Request.RawUrl: /Views/MyView.cshtml I have looked at the...

In MVC Razor, how can I correctly add querystring parameters to an html.actionlink?

asp.net-mvc,razor,asp.net-mvc-5
I have an MVC Razor page where I am trying to add a querystring parameter to the URL. <td> @Html.ActionLink(item.Student_Name, "Index", "FourCourseAuditDetails", new { filterByStudent = item.Student_Name}) </td> My desired outcome is: http://[server]/FourCourseAuditDetails/Index?filterByStudent="[item.Student_Name]", but when I test out the page, the anchor href attirubte looks like this: http://[server]/[route of current...

ASP.NET MVC TextArea doesn't respect row parameters

c#,html,asp.net-mvc,razor
I have the following TextArea which contains formatted XML: @Html.TextArea("ConfigXmlView", System.Xml.Linq.XDocument.Parse(Model.IdentifiFIConfiguration.ConfigXml).ToString(), 20, 50, null) The row parameter (20 in this case) seems to not affect the actual height of the text area at all. What could the problem be? And is there a way to automatically set the height of...

How to use more than 1 Model on a page by using asp.net mvc 5?

c#,razor,asp.net-mvc-5
I want to use 2 models. The first is on Index.cshtml page, and the second is on _Layout.cshtml page In the controller which contains the action public ActionResult Index(){...}, I declare some values and return it to View(). Like this: public ActionResult Index() { HomePageViewModel model = new HomePageViewModel(); //...

How to hide role based section in knockout component using asp.net MVC

javascript,asp.net,asp.net-mvc,razor,knockout-3.0
What is the best way to prevent user from seeing things like admin links in a knockout component? I don't want to make a client request if the user has right to see those links because it would expose this section on the client. The only way I can figure...

Does HTML Encoding have any cons?

asp.net-mvc,razor,encoding,utf-8,xss
I develop a project on ASP.NET MVC framework. All files and charsets are in UTF-8. I'm using model bindings and in some of my models the display property includes some accented chars or single/double quotes. As Razor engine automatically encodes helpers (ie. DisplayNameFor) the accented chars and quotes are encoded....

How do you Request[“”] with a Dynamic Variable? Request[“@Variable”]?

c#,asp.net,post,razor,request
I'm building a form, where the number of questions, or inputs on the form varies depending on the value in a database.Each input on the form is a radio type. The name of the tags are dynamic and are loaded from the database using @db.row.questionID which would look something like:...

How to assign C# variable to CSS class variable in ASP.NET MVC ActionLink

c#,css,asp.net-mvc,razor,dynamic-css
In the ActionLink code below, how can I assign a C# string variable to @class in the view in ASP.NET MVC 5? @Html.ActionLink("Manage List", "Index", new { @class = "DynamicClassName" }); I want to replace the static string @class = "DynamicClassName" with something dynamic, similar to @class = @myChangingColorClass //...

Display a tooltip with Html helper

html,asp.net,.net,asp.net-mvc,razor
I'd like add a tooltip to my razor view like this : @Html.Editor("Password", new { Title = "Doit contenir au moins une lettre majuscule, une minuscule, un chiffre et un caractère spécial" }) It is not working, If I just change the html helper by the input html tag, it...

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

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

foreach() over List in ViewBag recognizes T as object instead of actual type

c#,asp.net-mvc,razor
I am getting this strange error where Razor would say a property does not exist within an object. I sense I am doing a silly mistake, but I've been battling with this for a while but no luck. Any clues? Controller method: List<Conversations> lConversations = usr.conversations.OrderBy(o => o.active).ThenByDescending(o => o.updated_at).ToList().Select(i...

Prevent New Line Using Razor Conditional Statement

c#,asp.net-mvc,razor
I want to display some html content using the razor syntax, based on some variable contained in the ViewBag object. Current the content breaks to newline after the conditional statement. This is what I have: <h5>Apply salary @ViewBag.salaryStatus to associated objects?</h5> @if (ViewBag.salaryStatus == "Executed") { <h5>(This will overwrite old...

how to get the text inside using jquery if a contain more than one value

jquery,asp.net-mvc,razor
I have a table which will create dynamically during a button click <table id="diagnosis" style="display:none"> <tr> <td> <input id="diag-%" class="diag" style="width:200px" type="text" name="provider_diagnosis_dtls[#].diagnosis_code" value /> </td> <td> <input id="desc-%" class="diag_desc" style="width:500px" type="text" name="provider_diagnosis_dtls[#].diagnosis_desc" value /> </td> <td> <input id="level-%" type="text" name="provider_diagnosis_dtls[#].diagnosis_level" readonly...

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

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

Selecting Multiple Linq Fields Removing Column Names

c#,linq,razor
I need to select multiple fields into an enumerator to run a foreach in my Razor web app. In the controller, I have: ... cols = (from b in a.RefTable select new {b.Col1,b.Col2,b.Col3}), ... It returns the values correctly when I use: @foreach(var col in @item.cols) { @col } However,...

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

concatenating value to value in c# code — Asp.net MVC

javascript,c#,jquery,asp.net-mvc,razor
I have an anchor and I am assigning the the id to this anchor dynamically <li> <a href="#" name="offset" onclick="return so(this);" data-val="@Math.Round(Convert.ToDouble(ViewBag.lst[0].ca/2))" id='javascript:"[email protected](Convert.ToDouble(ViewBag.lst[0].ca / 2))"'>Last</a> </li> I supposed to get a3 or a4 or a5 because this @Math.Round(Convert.ToDouble(ViewBag.lst[0].ca / 2)) returns numeric value. But I am getting "a+3" or "a+4"....

Iterating over an ArrayList Always misses 1 entry

c#,asp.net,razor
When iterating over an ArrayList of strings to display on my WebForm using Razor one entry is never actually displayed. The code: <asp:UpdatePanel ID="TweetUpdatePanel" runat="server"> <ContentTemplate> <% ArrayList alList = GetLatest(); %> <ul> <% foreach (string tweet in alList) { %> <li> <asp:Literal ID="thisLiteral" runat="server"></asp:Literal> <% thisLiteral.Text = tweet; %>...

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

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

Bootstrap form-horizontal with form-group and razor html helper button alignment issues

html,css,twitter-bootstrap,razor
I am having issues correctly aligning buttons within with my razor markup. In a form-horizontal: <div class="row"> <div class="col-md-6"> <div class="form-group"> @html.labelfor @html.editorfor @html.validationmessagefor </div> </div> <div class="col-md-4"> <button class="btn btn-default" type="button" id="buttonId"> <span>Button Label</span> </button> </div> </div> The button aligns with the <label> element, and I am really looking...

MVC aspx example (as an alternative to using razor) [closed]

c#,asp.net-mvc,razor
In all the MVC examples I have seen, the razor view is being used, however I have seen mentions of using aspx views, but I have not seen any examples of it in an MVC project. Are there any reasons that using MVC implicitly assumes that razor is going to...

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

How to correclty use Views in different folders. (The view 'Index' or its master was not found or no view engine supports the searched locations)

c#,asp.net,asp.net-mvc,entity-framework,razor
My App has 3 big modules, one for the global admin, one for the company admin, and one for the company user. I want to split this into folders, both in the controllers folder and inside the views folder. When I add the controller with scaffolding. http://screencast.com/t/zxK5kaWLY It will automatically...

How to change name of .cshtml file on asp.net mvc?

c#,asp.net,asp.net-mvc,razor
I created a Asp.net mvc project on visual studios, In the many folder I get I have a folder called Home that has three .csthml files: about.cshtml, contact.cshtml, and index.cshtml. I would like to change about.cshtml to blah.cshtml and contact.chstml to lala.cshtml. I've tried to do it from properties but...

Jquery Tabs - return selected tab dynamically

c#,jquery,asp.net-mvc,asp.net-mvc-4,razor
On page load I would like to display selected tab dynamically. This is so validation is displayed for the correct tab. I have the following code: <script type="text/javascript"> $(document).ready(function () { var selectedTabId= $("#SelectedTab").val(); alert(selectedTabId); $('#tabs').tabs( { cache: false, beforeActivate: function (event, ui) { selectedTabId = ui.newPanel.attr('id'); $("#SelectedTab").val(selectedTabId); }, selected:...

Object reference not set to an instance of an object. with a non null object.

c#,asp.net-mvc,razor
Ok I'm having this problem that is driving me crazy, I'm doing a search for a website, and it works great on my machine but when I upload it to gearhost it just blow with this error : Object reference not set to an instance of an object. Description: An...

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

Ajax Post in mvc returns error all the time

ajax,json,asp.net-mvc,razor
I fairly new to Ajax post, and I wonder if someone could help me with why i keep getting the error message. VideoController [HttpPost] public ActionResult Check(string userid, string streamid) { return Json(new { success = true }); } The reason why the httppost is fairly empty yet is just...

Getting and passing MVC Model data to AngularJS controller

javascript,asp.net-mvc,angularjs,razor,asp.net-mvc-5
Hey guys so I'm pretty new to AngularJS and I'm at a loss here. Right now my MVC program uses Razor to display all the data in my .mdf database (i.e: @Html.DisplayFor(modelItem => item.LastName) ). However, I want to go mostly Angular. I am trying to use ng-repeat to display...

Convert int to date time

c#,razor
How can I convert an int to DateTime in a cshtml file using razor ? For example date=201411 should get converted to 2014 November. I tried to use: DateTime.TryParse(date); DateTime.ParseExact(date, "yyyymm"); ...

How to run javascript function in Razor MVC .net

javascript,asp.net-mvc,asp.net-mvc-4,razor
<script type="text/javascript"> @if (@Model.Invoice.InvoiceDate != null) { <text> function UTCToLocalTime(date) { var time = new Date(Date.parse(date)); var timeOffset = -((new Date()).getTimezoneOffset() / 60); time.setHours(d.getHours() + timeOffset); return time; } var date = @Model.Invoice.InvoiceDate UTCToLocalTime(date); </text> } </script> I am printing the above invoice and its open in a window....

Return to second to last URL in MVC (return View with previous filter conditions applied)?

c#,asp.net-mvc,razor,asp.net-mvc-5,grid.mvc
I'm working on an MVC5 application. On the home screen is a grid allowing users to view Data and be transferred to a number of Views for various actions on each record. One of these is an [EDIT]. The issue I'm encountering is as follows: due to the amount of...

Why does my MVC binding stop working when I assign a nested model to a variable?

c#,asp.net-mvc,asp.net-mvc-4,razor
I have code something like this contrived example in my MVC 4 razor view: @for (int i = 0; i < Model.NestedModel.Count; i++) { @Html.HiddenFor(model => modelModel.NestedModel[i].Id) @Html.EditorFor(model => Model.NestedModel[i].SomeProperty) } In which case everything works fine for me However, I wanted to tidy this up a little as the...

MVC Hidden field via HTML Helper in Form Post issue

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I have an issue when using a hidden field in an MVC Form Post. When the hidden field is generated via a HTML Helper it won't preserve it's value during the postback. But when using a HTML tag, it works. Unfortunately this one has taken me a whole day to...

Identifier starts immediately after numeric literal

jquery,ajax,razor
I'm trying to get the current logged in usersID in my jquery function var userID = @User.Identity.GetUserId(); Many answers on this page say that I have to do something like \"@User.Identity.GetUserId()\" But it dont seem to work, can someone tell me how to fix it. Its for my ajax post....

Disable select2 dropdown with knockout binding?

javascript,jquery,asp.net-mvc,razor,knockout.js
I have an MVC Razor project and in my view i have one Html.TextBoxFor with data-bind="disable: setRoot". This input is used by Select2 jquery plugin. My problem is that the disable binding is not working properly. This is my code: <div class="control-label">Category</div> <div class="input-group"> <div class="input-group-addon"><label><input data-bind="checked: setRoot" type="checkbox"> root</label>...

Using models correctly in partial razor views

c#,asp.net-mvc,razor
I have the following controller: public class WelcomeController { private IWelcomeService _service; public WelcomeController(IWelcomeService service) { _service = service; } public override ActionResult Index() { WelcomeIndexViewModel viewModel = new WelcomeIndexViewModel(); viewModel.LatestNewsArticles = _service.GetLatestNewsArticles(); return View(viewModel); } } And the following is the view model: public class WelcomeIndexViewModel { public IEnumerable<LatestNewsArticle>...

MVC View trying to parse 2 strings in Details view

asp.net-mvc,asp.net-mvc-4,razor
its an MVC razor project with entity framework, simple record view/edit/create in View, the details cshtml I want to read out just 2 of the record values and based on their contents, create a label. <h1 @if(Model.unittype == "PRP" && Model.name =="TTO"){string x = "CISCO";}else x = "---";>x</h1> not a...

Are intranet sites vulnerable to CSRF?

asp.net,asp.net-mvc,razor,asp.net-mvc-5
I have developed and deployed an MVC5 .NET app which runs within an intranet and uses LDAP to authenticate users. Since MVC 5 gives you the @Html.Antiforgery() by default I used them in every from. However in production where the app is running in multiple nodes I'm having problems with...

Format a multi-result single Json value

javascript,jquery,json,asp.net-mvc,razor
I have a change/getJson function that looks like this: $('#CountryId').change(function () { $.getJSON('@Url.Action("StateList", "Manage")', {id: $('#CountryId').val()}, function (data) { var items = '<option value="">Select a State</option>'; $.each(data.List, function (i, state) { items += "<option value='" + state.Value + "'>" + state.Text + "</option>"; }); $('#StateId').html(items); //Fail //console.log(">>>>" + data.LatLng.Latitude); //$('#Latitude').val(data.LatLng.Latitude);...

Merge C# Razor syntax with jQuery

c#,jquery,razor
I'm working on a project using C# razor engine and I wondering if it is possible to merge razor syntax with jQuery. Is that possible? An approach I have done is something like this: <script> $(document).ready(function() { @Html.Action("GoNext", "Actions", new { Id= ViewBag.Id, justifymessage = @:$("#msg").val(), Action = 3 })...

Is it possible to append html to a class or div using razor syntax

razor,html-helper,asp.net-mvc-views
I am coding a MVC 5 internet application and have a question in regards to accesssing html classes or divs via razor syntax. Is it possible to access a html class or div via razor syntax and append some html code to the class or div? Is there a html...

jQuery: How to traverse / Iterate over a list of object

javascript,jquery,asp.net-mvc,asp.net-mvc-4,razor
I'm using asp.net MVC4 for web app development. I would like to traverse a list of objects from a ViewModel. Below is the class of the object: public class User { public int Id {get; set;} public string Name {get; set;} public string Address {get; set;} public string Department {get;...

How to get attribute from actionlink

jquery,asp.net-mvc,razor,knockout.js
How can I get attributes from an ActionLink? I have this: <table> @foreach (var item in Model) { <tr> <td> @Html.ActionLink(item.Name, "Chat", "Home", new { id = item.ID }, new { @class = "Group" })<br /> </td> </tr> } </table> On the redirect page I need to get item.name Here's...

Rendering “~/bundles/jqueryval”

c#,asp.net-mvc,asp.net-mvc-4,razor
I need your help, I have written this code to render the "~/bundles/jqueryval" The view Code @model workflow.DataHolders.NewCompany <link href="@Url.Content("~/sharedfiles/css/forms/addnew.css")" rel="stylesheet" type="text/css" /> <div id="Add_container"> @if (!ViewData.ModelState.IsValid) { <div id="validationMessage">Please Correct The Errors Below</div> } @using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.ValidationMessage("CompanyName"); <span...

ASP.NET Vnext Tag Helpers for Areas

asp.net-mvc,razor,asp.net-mvc-5,tag-helpers
I may use <a href='/Area/Controller/action'> </a> in asp.net vnext but just want to know whether we can use tag helpers like <a asp-controller="ControllerName" asp-action="ActionName" asp-area="AreaName"> to redirect to the specific file in the area. Will any one guide me how to redirect to a file in area using tag helpers.?...

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

A potentially dangerous Request.Path in ASP.NET AjaxActionLink Request

c#,asp.net-mvc,razor
I have a cshtml view in an MVC ASP.NET application. I want to simply allow the user to click a button and provide a warning to the user before the action is carried out. The only way I know to acheive what I want is to use an AjaxActionLink like...

Jquery: Change contents of