Creating a drop down list in asp.net mvc3 - javascript

I am working on Simple Web Application using asp.net MVC4
I wonder to know how to create a drop down list in asp.net mvc4
In my application , I don't wanna use "ID_Sous_Type " but I wanna load a list from "Sous_Type" class
http://i.stack.imgur.com/qf1C4.jpg
I wrote this code in my index method :
var GenreLst = new List<string>();
var GenreQry = from d in secdb.SousTypes
orderby d.ID_Sous_Type
select d.Nom_Sous_Type;
GenreLst.AddRange(GenreQry.Distinct());
ViewBag.types = new SelectList(GenreLst); //Can't load this
In my View :
#Html.DropDownList("types")
UPDATE !
I am working on a form to retrieve data and save it in my table
I have two tables , Task and TaskType
For Task , The creation page is being like that .
http://i.stack.imgur.com/qf1C4.jpg
For the last field "ID_Sous_Type" , I would like to load list (from other table TaskType) to give a good user interface where the user can choose an appropriate type in better way (giving ID_Sous_Type is not that understandable )
For that , I would like to load the names of (TaskType) in Dropdown List
In my index controller :
I created .
var GenreLst = new List();
//Here i got all the names from TaskType table
var GenreQry = from d in secdb.SousTypes
orderby d.ID_Sous_Type
select d.Nom_Sous_Type;
GenreLst.AddRange(GenreQry.Distinct());
Then I added Ranges to easily get it
but I couldn't "Bind" it in Dropdown list , I wonder to know HOW !!

If i understand correctly your ViewBag.types is missing some vital information and that's why it's returning your list. It should be something like :
ViewBag.GenreId = new SelectList(db.Genres, "GenreId","Name");
See this article on the official .net site it should help you understand dropdown lists better.
http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-5

Related

Jquery exporting table to csv hidden table cells

I need to be able to export a HTML table to CSV. I found a snippet somewhere; it works but not entirely how I want it to.
In my table (in the fiddle) I have hidden fields, I just use quick n dirty inline styling and inline onclicks to swap between what you see.
What I want with the export is that it selects the table as currently displayed. so only the td's where style="display:table-cell". I know how to do this in normal JS.
document.querySelectorAll('td[style="display:table-cell"])');
but how can I do this using the code I have right now in the exportTableToCSV function?
(sorry but the text in the fiddle is in dutch as its a direct copy of the live version).
The fiddle:
http://jsfiddle.net/5hfcjkdh/
In your grabRow method you can filter out the hidden table cells using jQuery's :visible selector. Below is an example
function grabRow(i, row) {
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
//Added :visisble to ignore hidden ones
var $cols = $row.find('td:visible');
if (!$cols.length) $cols = $row.find('th:visible');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
Here's how i solved it. Decided to step away from a pure javascript solution to take processing stress off the client and instead handle it server side.
Because i already get the data from the database using a stored procedure i use this to just get the dataset again and convert it into an ViewExportModel so i have a TotalViewExport and a few trimmed variations (reuse most of them) based on a Selected variable i fill a different model.
Added to the excisting show function to update a Selected variable to keep track of the currently selected view.
When the user clicks Export table to excel it calls to the controller of the current page, IE. AlarmReport (so AlarmReportController) and i created the action ExportReports(int? SelectedView);
In addition i added CsvExport as a manager. This takes data results (so c# models/ iqueryables/ lists/ etc). and puts them into a Csv set. using the return type BinaryContent one can export a .csv file with this data.
The action ExportReports calls the stored procedure with the selectedview parameter. The result gets pumped into the correct model. this model is pumped into the CsvExport model as rows.
The filename is made based on the selected view + What object is selected + current date(yyyy-MM-dd). so for example "Total_Dolfinarium_2016-05-13". lets
lastly the action returns the .csv file as download using the BinaryContent Returntype and ExportToBytes from the CsvExport
The export part of this action is programmed like so(shortened to leave some checks out like multiple objects selected etc)(data and objectnames are gathred beforehand):
public ActionResult ExportCsv(CsvExport Data, string ObjectName, string Type){
var FileName = Type + "_" + ObjectName + "_" + DateTime.Now.ToString("yyyy/MM/dd");
return BinaryContent("text/csv", FileName + ".csv", Data.ExportToBytes());
}

Accessing objects/rows created in ASP.NET from Javascript

I create a table dynamically and add rows, labels etc to it.
I want to be able to access those rows to make either visible or hidden AND access labels to change content on the fly. So far the table and all info is created with no problem. I spent days trying to access the data from JS, but I keep getting NULL etc on objects using ALERT to test it. Here's a snippet example of my code...
ASP.NET (C#) code
mTable = new HtmlTable();
mTable.ID = "mTable";
aCell = new HtmlTableCell();
aLabel = new Label();
aLabel.ID = "aLabel";
aLabel.Text = "TEST";
aCell.Controls.Add(aLabel);
aRow = new HtmlTableRow();
aRow.ID = "r" + x;
aRow.Cells.Add(aCell);
mTable.Controls.Add(aRow);
Ive put the following code in a SCRIPT FILE etc and ive tried many styles.
alert(document.getElementById('<%=aLabel.ClientID%>'));
If you are using plain vanilla javascript, please look at the code sample here: How do I iterate through table rows and cells in javascript?
The code sample in the above link gets the table by id, which in your case is 'mTable' (from your c# code)
var table = document.getElementById('mTable');
// will return you a reference to the table object on the page
You also have to place the code to call your javascript function that accesses data on the 'mTable' on the document load event

Dynamically adding new item extremly slow

I use ASP.NET MVC and Razor. User needs to populate some form which consists of list of objects. So I pass list of empty objects from controller to view. This is part of my main view:
foreach ( var product in Model.Products )
{
Html.RenderPartial( "ProductPartial", product );
}
In ProductPartial user enters some fields for each product.
User can dynamically add or remove products from list. Removing I solved with jquery live function, and it is fine. But I have problem with adding new products.
I solved it in this way: On plus sign click javascript function calls controller action:
public ActionResult NewProduct()
{
Product product = new Product();
product.UniqueId = Guid.NewGuid();
return PartialView( "ProductPartial", product );
}
I need unique id for every product because I want to be able to access products from jquery by ids.
Adding works correctly, but it is extremly slow, since I go on server for every new product. Is there some good way to make it faster?
Well, instead of asking the server for more of the same HTML, you could use jQuery.clone();
In the example I'm copying the first product in the list and giving it a new id, and then adding the copy to the end of the list.
var newProductHtml = $('.MyProducts')[0].clone();
newProductHtml.attr('id', MyNewId);
newProductHtml.appendTo('.MyProductsContainer');

How to bind Knockout.js to existing table grid?

I'm a newbie to Knockout.js. I implemented the Knockout.js by loading data from ajax source and use foreach loop to create a table of the data. The tutorial i followed is here
http://www.dotnetcurry.com/ShowArticle.aspx?ID=933
My issue here is, due to the nature of my application, I find that the first load is better served from the server side using a grid component and I only want Knockout.js to take care of "Add" row, "Update" a row and "delete" a row.
My question is,
1) how do I replace the "first" load and populate the lookupCollection :ko.observableArray() in the article with the default data in the html table?
2) Related to #1. If the first load, the table layout with data is constructed from the server side, then how do I bind "foreach" to the grid so "add" can be performed on lookupCollection?
Thanks and again, I'm a newbie, I must be missing some key concepts here.
One way would be to pass your initial data into your view model. Since you are using asp.net it would look something like this:
//Dump raw data into javascript variable
var data = #Html.Raw(ViewBag.Data);
function ViewModel(data) {
var self = this;
//Unpack raw data
self.lookupCollection = ko.observableArray(data.lookupCollection);
}
//initialize view model
var viewModel = new ViewModel(data);
ko.applyBindings(viewModel);

How to work with Interlization concept in javascript or jQuery

In my project i am using Interlization by using spring mvc it's Working fine .But I want to show some alret() message to end user according to Selected Language .How i do this any one help me.I am using hidden Fields in my view layer but some performance issue is occur so any way to read properties file data by using javascript or jQuery
You can use nested objects. For example:
// Init a dictionary
var messages = {
en : {},
es : {}
};
// Populate
messages.en['welcome'] = 'welcome';
messages.es['welcome'] = 'bienvenido';
// Test
var lang = 'es';
alert(messages[lang]['welcome']);

Categories

Resources