razor,asp.net-mvc-5 , How to pass a value for input type=“number” to JS in Razor View

How to pass a value for input type=“number” to JS in Razor View


Tag: razor,asp.net-mvc-5

I have a view, here's a fragment of it:

@foreach (var item in Model.Items.ToList())
            <input type="checkbox" name="productIdCheckbox" value="@item.sLabel">
            @Html.DisplayFor(modelItem => item.sLabel)    
            @Html.DisplayFor(modelItem => item.Text)
            @Html.DisplayFor(modelItem => item.OEMCode)
            <input type="number" name="qty" id="qty" min="1" max="1000" step="1" value="@item.Quantity" />
            <input type="submit" data-url='@Url.Action("AddToCart", "Cart", new { id = item.Id, qty = // I DON'T KNOW HOW TO PASS IT HERE // })' class="addProductToCartBtn btn btn-success" value="Add to cart" />

This code invoke AddToCart method in CartController:

$('.addProductToCartBtn').click(function (event) {
    var url = $(this).data('url');
        url: url,
        type: 'GET',
        success: function (resultFrom_CartSummaryLine) {
            // some logic here..

But I can't pass to this method the value for qty input. How can I do it?

To be clear this is a method from CartController in which I want to pass a value for qty parameter:

public PartialViewResult AddToCart(CartModel cart, int id, int qty)
    GetItemListProcedure_Result item = _itemRepository.GetItemByItemId(id).FirstOrDefault();
    if (item != null)
        cart.AddItem(item, qty);
    return PartialView("_CartSummaryLine", cart);


You could have made the name="qty" number input using an HTML helper too. Something like this:

@Html.TextBoxFor(modelItem => modelItem.Quantity, new {type = "number"})

Then you should be able to retrieve the value just like any other input element.

Is that what you're asking for? Or do you specifically need to retrieve this value via JS?


Within your JS method, you can retrieve all of your values. Also, make it a POST ajax call so that you don't have to get the URL within the data-url. You can just add the parameters within the ajax call. Also add a [HttpPost] attribute to above your controller action method.

$('.addProductToCartBtn').click(function (event) {
        var url = $(this).data('url');
        var idVal = $('[name="productIdCheckbox"]').val();
        var qtyVal = $('#qty').val()
        var cart = {
            sLabel: $('#...'), //whatever your selector for this is
            Text: $('#...'),
            OEMcode: $('#...') 
            url: url,
            type: 'POST',
            data: {cart: cart, id: idVal, qty: qtyVal},
            success: function (resultFrom_CartSummaryLine) {
                // some logic here..


MVC: after export to excel, index action result is not getting called

I have one MVC application, in which export to excel functionality is given. I want to redirect Index action once export is finished. I have written below code but it not redirected to index action. what i missed here ? output = new MemoryStream(); workbook.Write(output); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",...

How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?

I have this ActionLink. @Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new {@class = "menuLink"}) I have to set routeValues to null because I don't know the value at compiletime. They are recieved from the selectedvalue of some dropdowns at runtime. Hence, I am trying to augment the routevalues at runtime with...

Binding my view model to a view causes all check boxes to be checked

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

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

Iterating over an ArrayList Always misses 1 entry

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

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

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

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

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

How to append Urls in angular routing?

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

Inherited Property of Model is always returning Null Value

I have a view which displays a radiobutton list on left side of the page and it also loads a partialview on right side of the page which consist of various filters to be selected before displaying a report in a popup window. The problem is that the property named...

Best approach to upgrade MVC3 web app to MVC5?

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

How to upgrade mvc2 to mvc5?

I've got an old project from a friend that he wants me to do redo. How ever that project is written in ASP.net mvc2. So When I try to open it in visual studio 2013 I can errors. Saying the file is incompatible. How would I go ahead and fix...

ASP.NET MVC DropDownList NullReferenceException

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

Convert string value to english word

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

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

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

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

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

MvcSiteMapProvider - Enhanced bootstrap dropdown menu

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

How to use ajax to post json string to controller method?

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

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

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

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

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

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

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

Rendering “~/bundles/jqueryval”

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

Knockout js unable to bind data using observableArray

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

Embedding a Silverlight App into a MVC

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

check for value null on razor syntax

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

Razor foreach loop loses item property

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

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

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

List/Array of dates to be used by jQuery

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

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

Is it possible to add Razor views to a deployed .NET MVC site? How would you do this?

Output Raw String in ASP.NET MVC Razor [duplicate]

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

Selecting Multiple Linq Fields Removing Column Names

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

ASP.NET MVC posting list from view to controller

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

Produce different serialized JSON for a given class in different scenarios

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

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

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

MVC route attribute no controller

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

MVC/Razor: Error at Viewbag.Title

I have two methods: public ActionResult Index() { var propList = db.Properties .Where(x => x.SiteVisibilityFlags.HasFlag(Enums.SiteVisibilityFlags.Corporate) || (x.SiteVisibilityFlagsOverride == true && x.SiteVisibilityFlagsOverrideValue.HasFlag(Enums.SiteVisibilityFlags.Corporate))) // just ones visible to 'Corporate' .ToList(); // Use view model var pDVMs = DomainModelsToViewModels(propList); return View(pDVMs); } public ActionResult Region(string id) // (regionId/marketId) { // make sure to...

Getting users from another AD Domain using PrincipalContext

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

Why is my View not displaying value of ViewBag?

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

Identifier starts immediately after numeric literal

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

Request.Form is null on making button as disabled

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

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

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

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

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

Web API AuthorizeAttribute does not return custom response

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

Linq Conditional DefaultIfEmpty query filter

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

Can't get Editor Template to Work

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

How to get routevalues from URL with htmlhelpers or JavaScript?

I have this MVC MapRoute routes.MapRoute( name: "Authenticated", url: "{controller}/{action}/{foo}/{bar}", defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" } ); And URL http://localhost/mysite/controller/action/2/1 How can I with JavaScript recieve the 2 and 1? I would prefer a solution with as little substring work...

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

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

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

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

Strange situation, Visual Studio debugging ran through action to view but nothing returned to browser

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