I'm working on MVC3 project.
At my controller I already have a code that gets the Descr column from StockClass table. After that I fill a ViewBag with this list in order to retrieve it from the view and populate the dropdown list.
Currently is working fine but only shows Descr field (obviously). What i want is populate the dropdown list with two fields (Code and Descr) in this format: "code - descr".
I tried several ways but i cannot find the way to code the #Html helper correctly.
In my controller...
var oc = dba.StockClass.OrderBy(q => q.Code).ToList();
ViewBag.OrderClass = new SelectList(oc, "StockClassId", "Descr");
In my view....
#Html.DropDownList("StockClassID", (SelectList)ViewBag.OrderClass)
Could you please help me?
I don't believe there is an HTML Helper which will do that for you, but you can get what you're after like this:
var oc = dba.StockClass
.OrderBy(q => q.Code)
.ToDictionary(q => q.StockClassId, q => q.Code + " - " + q.Descr);
ViewBag.OrderClass = new SelectList(oc, "Key", "Value");
This also has the advantage of making the uses of StockClassId, Code and Descr refactor-friendly - if you rename those properties you won't be able to compile without updating this bit of code to match.
Related
I'm trying to dynamically build an action link for adding items to a database in Laravel. The problem is that I need to pass a parameter with category_id, which I only get after selecting the category in html select element.
I thought about using the even onChange() on select element, and then building up the link in js function, and finally setting it to "a" element with the help of js selector. However this approach doesn't work.
var link = "{{ action('ItemController#create', [ 'id' =>"+selectedId.value+"]) }}";
document.getElementById("AddItemLink").href = link;
Is producing: http://localhost:8000/item/create/+selectedId.value+
What I need to get is: http://localhost:8000/item/create/8
If I do console.log(selectedId.value), the output is correct - 8.
Any ideas how to deal with this?
You can do that,
var link = "/item/create/"+ selectedId.value;
document.getElementById("AddItemLink").href = link;
I want to insert the values of an Umbraco.Tags datatype field into my razor output for each record from a LINQ query of my content. I'm having trouble finding the right syntax. I realize it should be a string array but everything I have tried fails.
In the page for the individual content I have been able to use the following where the content field is name "Tags".
var tags = CurrentPage.Tags;
The LINQ query is complex, but I am simply trying to add the tags to the output so that I can search inside the page for specific records on the client side. I have removed most of the query to make it easier to read.
var products = Model.Content.Site().Descendants<PenList>().First().Children("penProduct")
.Where(x => x.IsVisible())
.OfType<PenProduct>()
.Select(x => new ProductSearchResultItem() {
FilterText = x.ProductName + " " + x.ProductDescription.ToString() + " " + x.CompanyName.NullSafeToString() + " " + x.ProductType.ToString()
+ " " + (x.Parent.GetProperty("tags") != null ? x.Parent.GetProperty("tags").Value : string.Empty)})
I have also tried just getting x.Tags or x.GetProperty("tags") with no success. Any suggestions would be appreciated.
Is the tags property on the penProduct doc type or the penList? It looks like you're looking for it on the penList.
But I would think it would behave like any other string. I don't normally use typed modals, but to get a list of the tag values in my views I use:
var tags = Model.Content.GetPropertyValue<string>("tags", "").Split(',');
Since the field is actually a string array I had to use the following code to get the property as a string array generic otherwise it would return the text of the type "System.String[]".
x.GetPropertyValue<string[]>("tags")
I'm currently trying to implement AJAX results filtering on a certain page.
I created the dropdowns(on the client side), so that they have the umbraco prevalue id as their value.
I will then send this id to the server, rather than the text value. Then I loop through my content to find items with this same id.
The problem, however, is that I can't figure out how to get the value id from the property. Everything either returns the text value, or just a 0 value.
This is being performed in an ApiController.
These are all of the options I've tried:
IPublishedContent root = Umbraco.TypedContentAtRoot().First();
var downloads = root.Children.Where(q => q.Name == "Downloads").SingleOrDefault();
foreach (var item in downloads.Children)
{
var test = item.GetPropertyValue<int>("classification");
var testing = item.GetProperty("classification");
var testVal = testing.DataValue;
var testValToo = testing.GetValue<int>();
var testThree = testing.Value;
}
These are the results in order:
- 0
- IPublishedProperty
- "textValue"
- 0
- "textValue"
Is it possible to get the selected value id from a dropdownlist property? Or is string matching my only option to compare values?
EDIT:
Nevermind, found the solution. Posting the answer here, in case someone else needs it.
I was using the data type dropdownlist. I should have been using dropdownlist:publishing keys.
dropdownlist only ever returns a value. dropdownlist:publishing keys, however, returns the prevalue id, rather than the text value.
Source
Something like this perhaps.
library.GetPreValueAsString(node.GetProperty<int>("sectionType")).ToLower()
Given a jqGrid populated with local data and created with the option of idPrefix:"custTable" , all the generated rows get the prefix in the html id i.e. custTableRow_1 custTableRow_2 etc. Does this idPrefix'ed version of the id need to be passed in to the jqGrid methods, if so which ones?
for example to delete a row with deleteRowData does it need the prefixed id? how about setRowData or addRowData? when adding after row x it seems to need the prefixed for the srcrowid parameter. How about multiselect rows?
If I delete a row using the prefixed id of the row it disappears from the display but when I reload the grid the delete item shows up again in the grid, like it wasn't removed. This doesn't happen when idPrefix is not used.
thanks for any help.
The option idPrefix was introduced to hold ids on the HTML page unique even you have on the page the ids like the rowids loaded from the server. Typical example is two grids with the data loaded from the server. Let us you have two tables in the database where you use IDENTITY or AUTOINCREMENT in the definition of the PRIMARY KEY. In the case the primary key will be generated automatically in the table and will be unique inside the table, but there are not unique over the tables. So if you would use the primary keys as ids of the grids and place on one page two grids you can have id duplicates.
To solve the problem you can use idPrefix: "a" as additional option in the first grid and use idPrefix: "b" in the second grid. In the case locally jqGrid will uses everywhere ids with the prefix, but the prefix will be cut if the ids will be sent to the server.
So you will see locally in all callbacks (events) and in all methods (like setRowData, addRowData etc) the ids with the prefix, but on the server side the ids the prefixes will be removed immediately before sending to the server.
I recommend you additionally to read another answer about the restrictions in the ids which I posted today.
UPDATED: I looked through the code which you posed on jsfiddle and found some clear bugs in your code. You current code
1) use wrong algorithm to generate id of the new row. For example the following code
// generic way to create an animal
function newAnimal(collection, defaults) {
var next = collection.length + 1;
var newpet = {
id : next,
name: defaults.name + next,
breed: defaults.breed
};
return newpet;
}
use collection.length + 1 for the new id. It's wrong if you allows to delete the items. By adding of two items, deleting one from there and adding new item one more time follows to id duplicates. Instead of that it's more safe to use some variable which will be only incremented. You can use $.jgrid.randId() for example which code is very simple.
2) you call addRowData with adding a prefix manually (see dogsPrefix+newdog.id below). It's wrong because jqGrid adds the prefix one more time to the rows.
// add dog button actions
$('#dogAddAtEnd').click(function() {
var newdog = newAnimal(dogs, dogDefaults);
dogs.push(newdog);
dogAdded();
dogsTable.jqGrid('addRowData', dogsPrefix+newdog.id, newdog);
});
Probably there are more problems, but at least these problems can explain the problems which you described.
UPDATED 2: I examined new demo which you posted. It has still the lines
grid.jqGrid('addRowData', newanimal.id, newanimal,
"after", prefix+ followingId);
and
dogsTable.jqGrid('addRowData', dogsPrefix+newdog.id, newdog);
which must be fixed to
grid.jqGrid('addRowData', newanimal.id, newanimal,
"after", followingId);
and
dogsTable.jqGrid('addRowData', newdog.id, newdog);
Nevertheless I tested the demo after the changes and found bugs in code of addRowData, delRowData and setRowData. The problem are in the line of the delRowData and the same line of setRowData
var pos = $t.p._index[rowid];
can be fixed to the following
var id = $.jgrid.stripPref($t.p.idPrefix, rowid), pos = $t.p._index[id];
Inside of addRowData I suggest to include the line
var id = rowid; // pure id without prefix
before the line
rowid = t.p.idPrefix + rowid;
of addRowData. Another tow lines of addRowData
lcdata[t.p.localReader.id] = rowid;
t.p._index[rowid] = t.p.data.length;
should be changed to
lcdata[t.p.localReader.id] = id;
t.p._index[id] = t.p.data.length;
where unprefixed id will be used.
The modified code of you demo which uses the fixed version of jquery.jqGrid.src.js you can test here.
I will post my bug report to trirand later to inform the developer of the jqGrid. I hope that soon the bug fix will be included in the main code of jqGrid.
Additionally I recommend you to use $.jgrid.stripPref method to strip prefixes from the rowids. For example the function
//general delete selected
function deleteSelectedAnimal(list, grid, prefix)
{
var sel = grid.jqGrid('getGridParam', 'selrow');
if (sel.length)
{
var gridrow = sel;
//get the unprefixed model id
var modelid = gridrow;
if (prefix.length !== 0)
{
modelid = modelid.split(prefix)[1];
}
// make it a numeric
modelid = Number(modelid);
//delete the row in the collection
list = RemoveAnimal(list, modelid);
//delete the row in the grid
grid.jqGrid('delRowData', gridrow);
}
}
from your demo can be rewritten to the following
//general delete selected
function deleteSelectedAnimal(list, grid)
{
var sel = grid.jqGrid('getGridParam', 'selrow'),
gridPrefix = grid.jqGrid('getGridParam', 'idPrefix');
if (sel !== null)
{
//delete the row in the collection
// ??? the gogs list will be not modified in the way !!!
list = RemoveAnimal(list, $.jgrid.stripPref(gridPrefix, sel));
//delete the row in the grid
grid.jqGrid('delRowData', sel);
}
}
I am not sure that the line list = RemoveAnimal(list, $.jgrid.stripPref(gridPrefix, sel)); or the function RemoveAnimal do what you want, but it's not a problem which connected with jqGrid.
One more small remark about your code. You use already in the objects which you add to the grid the id property. It's the same name as defined in the localReader.id. In the case the data from the id property will be used as id attribute of the grid rows (<tr>). The local data parameter will save the id additionally to other properties which are build from the name property of the items of colModel. So I see no sense to define hidden column
{ key: true, name: 'id', align: 'left', hidden: true }
How you can see on the demo all stay works exactly as before if you remove id column from the grids which you use.
UPDATED 3: As promised before I posted the corresponding bug report here.
when using a MVC 3 collection that uses IEnumerable, is there a way to make small queries work to find single values? I've been experimenting with little success.
I have a collection of settings that have descriptions and settings. The problem is exposing one of them, as each is unique. I've tried something like this:
var appl = _service.GetSettings(id, app); //Call to service layer & repository
appl.Select(a => a.setting_value.Where(a.setting_name.StartsWith("Login")));
With little success (unless I'm missing something). Is it possible to select one item from an enumerable collection and either pass it to a ViewBag or ViewData object? What I would like to do is something like the following:
var appl = _service.GetSettings(id, app); //Call to service layer & repository
ViewBag.Login = appl.Select(a => a.setting_value.Where(a.setting_name.StartsWith("Login")));
And pass this to the view, since I have a view that now combines a collection with single values.
The following seems to work within the view:
Application Name #Html.TextBox("application_name", #Model.FirstOrDefault().app_name)
But I'm not sure if this violates separation of concerns. Am I on the wrong path here? Thank you!
EDIT: Here is what I needed. The answers below got me very very close +1 +1
ViewBag.Login = appl.Where(a => a.setting_name.StartsWith("Login")).FirstOrDefault().setting_value
ViewBag.Login = appl.Select(a => a.setting_value.Where(a.setting_name.StartsWith("Login"))).FirstOrDefault();
This will select the first object that matches your criteria and return a single result or null
var appl = _service.GetSettings(id, app);
ViewBag.Login = appl
.Where(a => a.setting_name.StartsWith("Login"))
.FirstOrDefault();