I am new to MVC and trying to build put a simple web application.
I have a Class - ListItems
public class ListItems
{
public string Display { get; set; }
public string Value { get; set; }
public string Area { get; set; }
public string LongDescription { get; set; }
}
From controller -
I am using function to populate values of dropdownlist .Data is populated to ListItems
List<ListItems> Lst= new List<ListItems>();
string query = #"SELECT DISTINCT A.[COLA],A.[COLB],[COLC] FROM tableA ";
getting to Dataset ds
ListItems item;
foreach (DataRow row in ds.Tables[0].Rows)
{
item = new ListItems();
item.Value = DBBase.ConvertToString(row["COLA"], string.Empty);
item.Display = DBBase.ConvertToString(row["COLB"], string.Empty);
item.Area = DBBase.ConvertToString(row["COLC"], string.Empty);
statusList.Add(item);
}
In View
#Html.DropDownListFor(model => model.COLA, new SelectList(Model.VenueList, "Value", "Display","Area"), "- Please select a Value-", new { id = "lstA" })
Now, I need to get value of 'Area' Column of dropdownlist 'lstA' in javascript
on button click
In javascript
function AB(){
$('#lstVenue :selected').val(); // this gives selected value
}
How to get value of column 'Area' ?
Since a dropdown list cannot bind 3 values, you have to set Value and Area to values of options with a unique character (I used '#' as an example) like this:
// Make sure '#' doesn't appear on "Value" nor "Area"
#Html.DropDownListFor(model => model.COLA, new SelectList(Model.VenueList.Select(v => new { Display = v.Display, Value = string.Concat(v.Value, "#", v.Area) }), "Value", "Display"), "- Please select a Value-", new { id = "lstA" })
Then, you can get both "Value" and "Area" with JavaScript(jQuery) like this:
var selected = $('#lstA :selected').val();
var splited = selected.split("#");
var value = splited[0];
var area = splited[1];
if (area == "0"){
// Do something
}
Related
I've been trying to get ng-table(angular directive) work with a web api (ASP.NET MVC). I can load and page the data but the sorting or filtering won't work.
The weird thing is that the sorting or filtering will look like this in the URL:
http://localhost:46278/api/rating?count=10&filter%5Brating.name%5D=fs&page=1&sorting%5Brating.description%5D=asc
If you would "format" it, it would look like this:
filter[rating.name] = fs
sorting[rating.description] = asc
I tried to get them with a string array or a dictionary (KeyValuePair)
But I can't get the values. So I can never filter or sort the data.
I hope you can give me some advice! I appreciate your help!
I wrote a helper class to deal with this. The URL isn't formatted in a way WebAPI expects, so couldn't get the ModelBinder to parse it automatically.
From your controller, call the helpers and provide the entire URL:
// Parse sortings
var sortings = TableHelpers.ParseSortings(Request.RequestUri).ToList();
// Parse filters
var filters = TableHelpers.ParseFilters(Request.RequestUri).ToList();
And the helper class
public static class TableHelpers
{
public static IEnumerable<TableSorting> ParseSortings(Uri requestUri)
{
var regex = new Regex("sorting%5B(.+?)%5D=(asc|desc)");
var matches = regex.Matches(requestUri.AbsoluteUri);
return from Match match in matches
select new TableSorting {Field = match.Groups[1].Value, Order = match.Groups[2].Value};
}
public static IEnumerable<TableFilter> ParseFilters(Uri requestUri)
{
var regex = new Regex("filter%5B(.+?)%5D=(.+?)(?:&|\\z)");
var matches = regex.Matches(requestUri.AbsoluteUri);
return from Match match in matches
select new TableFilter {Field = match.Groups[1].Value, Value = match.Groups[2].Value};
}
}
public class TableSorting
{
public string Field { get; set; }
public string Order { get; set; }
}
public class TableFilter
{
public string Field { get; set; }
public string Value { get; set; }
}
are you asking about directive syntax or your api?
in ng-table directive, insert in <td> tag sorting or/and filtering attrs, like:
<td width="10%" data-title="'NUM'|translate" filter="{ 'num': 'text' }" sortable="'num'"><span>{{item.num}}</span></td>
When I send data (values and dates) from function (hard coded), everything is ok, json file is populated, and I see the chart, but when I send data from database, there is no chart but I see that json file is also populeted.
Here is code:
public class YearlyStat
{
public string year { get; set; }
public double value { get; set; }
}
public ActionResult Statistics(int? id)
{
//var result = db.pricepoints.Where(r => r.commodityID.Equals(id));
var items = from item in db.pricepoints
where (item.commodityID == id)
select item;
var stats = new List<YearlyStat>();
foreach (var item in items)
{
stats.Add(new YearlyStat
{
year = item.date_of_price.ToShortDateString(),
value = item.value
});
}
//but this works
//string s = "2.2.2002";
//double v = 20.20;
//stats.Add(new YearlyStat { year = s, value = v });
//or
//stats.Add(new YearlyStat { year = "2.2.2002", value = 20.20 });
return Json(stats, JsonRequestBehavior.AllowGet);
}
Types are string and double in both cases.
Check your javascript file. Probably is missing the parameter id. If you are using ajax take a look at the parameters ;)
When I send data (values and dates) from function (hard coded), everything is ok, json file is populated, and I see the chart, but when I send data from database, there is no chart but I see that json file is also populeted.
Here is code:
public class YearlyStat
{
public string year { get; set; }
public double value { get; set; }
}
public ActionResult Statistics(int? id)
{
//var result = db.pricepoints.Where(r => r.commodityID.Equals(id));
var items = from item in db.pricepoints
where (item.commodityID == id)
select item;
var stats = new List<YearlyStat>();
foreach (var item in items)
{
stats.Add(new YearlyStat
{
year = item.date_of_price.ToShortDateString(),
value = item.value
});
}
//but this works
//string s = "2.2.2002";
//double v = 20.20;
//stats.Add(new YearlyStat { year = s, value = v });
//or
//stats.Add(new YearlyStat { year = "2.2.2002", value = 20.20 });
return Json(stats, JsonRequestBehavior.AllowGet);
}
Types are string and double in both cases.
I get it :D
Problem is in my JavaScript, i didn't send 'id' parametar to Statistics function.
<script type="text/javascript">
$.get('#Url.Action("Statistics")', function(result){
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'myfirstchart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data:
result
,
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['value'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Value','Date']
});
});
It works when i put:
#Url.Action("Statistics", new { id = ViewBag.commodityID })
Now im happy man :D
I have a Region class like this:
public class Region
{
public int Id { get; set; }
public int Name { get; set; }
public int ParentId { get; set; }
}
And Person has region:
public class Person
{
public int Id { get; set; }
public int Name { get; set; }
public int SurName { get; set; }
public int RegionId { get; set; }
}
But, it is not like tree node. There are only 2 floors. Countries and it's sub regions - cities. I use bootstrap template.
I collect this regions like this list:
Country1 //need to disable this
City1
City2
City3
Country2 //need to disable this
City1
City2
In person create action:
Viewbag.Regions = new SelectList(MyRepository.LoadRegions(), "Id", "Name");
And in view:
#Html.DropDownListFor(model => model.RegionId, ViewBag.Regions as IEnumerable<SelectListItem>, "-", new { data_rel = "chosen", #id = "region" })
Finally, I need when dropdown opens, to disable countries, it is possible to select only cities.
How can I disable elements in dropdownlis which parentId == 0 ?
One approach you could take is to load up the Regions, remove the Parent items, and then assign the SelectList to the Viewbag.
var regions = MyRepository.LoadRegions();
/* remove parent items from regions */
ViewBag.Regions = new SelectList(regions, "Id", "Name");
EDIT I previously misunderstood the question. You want to have headers that aren't selectable. I found this question about MVC supporting OptGroups (which I think will accomplish what you're going for). Turns out the base Html.DropDown helper doesn't support it but you can write a custom one, and in the linked question there is a sample of a custom helper for this case.
I have a listbox that I am populating using a foreach. (Long explanation of why I need to do this.)
I need to escape the string because fname and lname can contain special characters, like ' or ".
foreach (var cust in item.Customers)
{
var custString = string.Format("{0}%#%{1}%#%{2}", cust.CustID, cust.LName, cust.FName);
<option value="#custString">#cust.DisplayName</option>
}
Is there any way to do a javascript escape of custString right after setting the value? Or is there there a preferred C# way of escaping that will work well with javascript's unescape, which I am using to unescape these chars.
That's what the AttributeEncode helper does:
<option value="#Html.AttributeEncode(custString)">#cust.DisplayName</option>
But hey, what are you doing? foreach loop to generate a dropdown list????
Try the Html.DropDownListFor helper and stop the bleeding inside your view before its too late. This helper does what its name suggests. And takes care of encoding and escaping and whatever.
So simply define a view model:
public class MyViewModel
{
public string CustomerId { get; set; }
public IEnumerable<SelectListItem> Customers { get; set; }
}
then go ahead and have your controller action populate and pass this view model to the view:
public ActionResult Index()
{
IEnumerable<Customer> customers = ... fetch the domain model from your DAL or something
// map to a view model:
var viewModel = new MyViewModel
{
Customers = customers.Select(x => new SelectListItem
{
Value = x.CustID,
Text = string.Format("{0}%#%{1}%#%{2}", x.CustID, x.LName, x.FName)
})
};
// pass the view model to the view:
return View(viewModel);
}
and inside the view, use the DropDownListFor helper when you need to generate a dropdown list:
#Html.DropDownListFor(x => x.CustomerId, Model.Customers)