FAQ Database Discussion Community


How do you send data to controller with ajax.beginform?

ajax,asp.net-mvc-4,razor,model-view-controller,model
This is my method on controller "sale" [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Models.account account) { Models.sale creaventa = new Models.sale(); //creaventa.account = cliente; creaventa.createdon = DateTime.Now; creaventa.idaccount = account.id; creaventa.modifiedon = DateTime.Now; creaventa.status = 0; context.sales.Add(creaventa); context.SaveChanges(); // return "venta creada"; return View(); } and this is the partial view @model...

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

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

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

MVC - Changing default text in dropdown

asp.net-mvc,razor,enums,html.dropdownlistfor
I have a view model that contains an enum: public class PasswordChangerIndexViewModel { public enum DatabaseTypes { Main = 10, Florida = 20, Illinois = 30, Missouri = 40, NewHampshire = 50, NewJersey = 60, Oklahome = 70 }; [DisplayName("Database")] public DatabaseTypes DatabaseType { get; set; } } And in...

POST to MVC controller IEnumerable nested Model is null when I don't select checkboxes in order

c#,asp.net-mvc,razor,visual-studio-2013,asp.net-mvc-5
When I'm trying to get values in Post the values of checkboxes are set to NULL when I don't check then in order (1, 2, 3, etc). I need to select any of them in no order (i.e. 4, 5). MODEL: public class AssignUsersViewModel { [Display(Name = "Check to select")]...

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

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

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

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

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

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

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

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

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

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

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

DropDownList Change() doesn't seem to fire

javascript,c#,asp.net-mvc,razor
So, I have been bashing my head against the desk for a day now. I know this may be a simple question, but the answer is eluding me. Help? I have a DropDownList on a modal that is built from a partial view. I need to handle the .Change() on...

List/Array of dates to be used by jQuery

jquery,asp.net,arrays,razor,webmatrix
I'm after some guidance. I have a SQL select statement which pulls a bunch of dates out of my database. I then need to put them into an array or list (i'm not sure which would be best) so that it can be consumed by a jquery script (which will...

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

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

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

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

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

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

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

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

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

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

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

Is possible to create htmlhelpers dynamically?

javascript,html,asp.net-mvc,razor
I wanted to create a htmlhelpers elements depending on the value of dropdown list. Here is the code: Dropdown <select id="pracownicy"> <option value="biurowy" style="color: black">Pracownik biurowy</option> <option value="przewodnik" style="color: black">Przewodnik</option> </select> and script be like: <script> function pracownicy() { var x = document.getElementById("pracownicy"); if (x.value.equalTo("biurowy")) { } if (x.value.equalTo("przewodnik")) {...

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

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

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

ASP.NET MVC DropDownList NullReferenceException

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

Using Razor Syntax within JavaScript Conditional Statment

javascript,c#,asp.net-mvc,razor,conditional
In an index.cshtml I have the following working code similar to: <script type="text/javascript"> if ('@Model.SomeCondition' === 'True'){ Do Something(); } </script> The === 'True' seems like an odd hack to me to force Razor and JavaScript to get along. How can I refactor to use === true? This doesn't give...

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

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

Transform Querystring to RouteValue in Razor View

c#,jquery,html,asp.net-mvc,razor
I'm stuck with a very basic detail in a view. I want to be able to let the user filter the results in the Index view. To do this I've created a dropdown list, which gets populated thourgh my viewmodel: @using (Html.BeginForm("Index", "Captains", FormMethod.Get)) { <div class="row"> <div class="dropdown"> @Html.DropDownList("Name",...

Return to the same view when no image is selected

asp.net-mvc-4,razor,json.net,entity-framework-5,c#-5.0
I have an upload control. But if the user didnt select an image and the press on the upload button, the user will get an message that he/she has to go back and try again, like this: if (isSavedSuccessfully) { return Redirect(Url.Action("Edit", "Account") + "#tabs-2"); } else { return Json(new...

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

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

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

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

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

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

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

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

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

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

my model binding is working even If I didn't show it in html

c#,asp.net,asp.net-mvc,razor,model-binding
I have a form that can be reached by different ways. In the URL, if user comes with ?data=johndoe (example), I didn't want to deal with another property, so I didn't show it to user and I don't care of this property. Because I use the same form and the...

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

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

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

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

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

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

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

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?

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

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

Partial View's checkbox state not returned to controller

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I have a main view whose Model is of type FacilityViewModel. The main view loads a partial view that also contains a partial view. Both partial views have a model of type FiltersViewModel. The most nested partial view loops through a dictionary and creates a checkbox for each item to...

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

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

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

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

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

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

How do I convert an array from the ViewBag to a JScript array using Razor Syntax? [duplicate]

javascript,c#,arrays,asp.net-mvc,razor
This question already has an answer here: How to return Json object from MVC controller to view 3 answers I am trying to re-code the following razor syntax to be workable code and am stuck: var ServiceIndex = @ViewBag.ServiceID ; var ServiceName = @ViewBag.ServiceName ; var ServiceNotes = @ViewBag.ServiceNotes...

Request.Form is null on making button as disabled

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

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

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

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

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

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

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

Jquery: Change contents of