ASP.NET Core MVC : #Html.DropDownList on change pass ViewBag as parameter - c#

I am creating an ASP.NET Core MVC application. I have a #Html.DropDownList and in the on change function, I want to pass as parameter a ViewBag value
#Html.DropDownList("PageSize", new SelectList(new Dictionary<string, int> { { "10", 10 }, { "20", 20 }, { "30", 30 }, { "40", 40 }, { "50", 50 }, { "100", 100 } }, "Key", "Value", Convert.ToString(ViewBag.PageSize)), new { id = "SearchPageSize", style = "width: 100px;", #onchange = "AAA(ViewBag.CurrentSort)" })
The function AAA is never called, and I get this error
Uncaught ReferenceError: ViewBag is not defined at HTMLSelectElement.onchange
It does not like how I am passing the parameter ViewBag.CurrentSort
How can I solve this?
Thanks

The issue is the context, which is c#.
Since the property being set is from the c# side, no # is required.
To get the quotes around the parameter, use string.Format.
onchange=string.Format("AAA('{0}')", ViewBag.CurrentSort)

Related

Filtering query from database

I have a problem because I am new to mongodb and c#. I hope you can help.
I need to add a filter when retrieving data from database. Objects in ProductAttributeCombinations in the database exist more than once. I'm getting data from these objects to the variable named ProductAttributeText, but it comes as a list because there is more than one data in the object. What I need to do is to compare the value under a different object in the database with the values ​​under this object and get the data accordingly.
My codes where I get the data
var querySpec = await _productRepository.Collection
.Aggregate()
.Unwind(x => x.ProductAttributeMappings)
.Project(new BsonDocument {
{ "ProductAttributeId", "$ProductAttributeMappings.ProductAttributeId" },
{ "ProductAttributeValues","$ProductAttributeMappings.ProductAttributeValues.Name" },
{ "ProductAttributeCombination","$ProductAttributeCombinations.Text" },
})
.Unwind("ProductAttributeValues")
.Group(new BsonDocument {
{"_id",
new BsonDocument {
{ "ProductAttributeId", "$ProductAttributeId" },
{ "ProductAttributeName", "$ProductAttributeValues" },
{ "ProductAttributeText", "$ProductAttributeCombination" },
}
},
{"count",
new BsonDocument {
{ "$sum" , 1}
}
}
}).ToListAsync();
If one of the list elements returned to me is like this
{{ "_id" : { "ProductAttributeId" : "60daf1f56b2621a0b7942eac", "ProductAttributeName" : "50", "ProductAttributeText" : ["30", "30", "30", "3", "3", "3", "30", "30", "30"] }, "count" : 3 }}
When I add the filtering like this and add it as Match(filterAttr) to my code, QuerySpec returns null. Am I making a mistake in filtering?
var filterDefAttr = new FilterDefinitionBuilder<BsonDocument>();
var filterAttr = (filterDefAttr.Eq("ProductAttributeCombinations.Attributes.Value", "ProductAttributeMappings.ProductAttributeValues._id"));

Send the content-type to webapi from kenod dropdown list

I need to send the contentType as "application/json" to webApi controller. below is the code which i used and it is not working.
#(Html.Kendo().DropDownList()
.Name("ddlPatientClass").AutoBind(true)
.HtmlAttributes(new { style = "width: 67px!important;" })
.DataTextField("ModuleName")
.DataValueField("RoleId")
.ContentType("application/json")
.DataSource(source =>
{
source.Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "MedicalVisit", Action = "GetPatientClass" })).Type(HttpVerbs.Get));//.Type(HttpVerbs.Get).Data("ModuleParamCP"));
})
)
Instead of #Htmlhelper class, you can use below Kendo UI JQyery dropdown to bind JSON data as below.
HTML
<input id="ddlPatientClass" name="ddlPatientClass" class="custom-select" style="width: 100%;" />
JQuery
$(document).ready(function () {
var data = [
{ text: "0", value: "0" },
{ text: "10", value: "10" },
{ text: "25", value: "25" },
{ text: "30", value: "30" },
{ text: "100", value: "100" }
];
// This data you can get from WebApi - using Ajax call
// After get JSON data from webApi - you can create DropDownList as below
$("#ddlPatientClass").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
index: 0,
optionLabel: "-- Choose % --",
});
});

Passing objects as url parameters c#

I want to pass a Filters object as well as other things as query parameters into a url, for example something like:
{
"clientId": 2,
"date": "2017-01-01",
"filters": {
"days": { "monday", "tuesday", "wednesday" },
"months": { "january", "february" }
}
But I don't know how an object like filters in this example could get passed in by a query string parameter. I know you would normally have something that looks like:
https://localhost/path?clientId=2&date=2017-01-01&filters= ?????
Thanks!
Maybe is better to POST your data if they are complex instead sending as query string parameter. But anyway, if you want to send as query string you can do following:
Convert object into string
Encode string
Append as parameter
For following object (converted into string and removed spaces):
{
"clientId": 2,
"date": "2017-01-01",
"filters": {
"days": { "monday", "tuesday", "wednesday" },
"months": { "january", "february" }
}
I created encoded text which is safe to sending over network:
%7B%0A%22clientId%22%3A%202%2C%0A%22date%22%3A%20%222017-01-01%22%2C%0A%22filters%22%3A%20%7B%0A%22days%22%3A%20%7B%20%22monday%22%2C%20%22tuesday%22%2C%20%22wednesday%22%20%7D%2C%0A%22months%22%3A%20%7B%20%22january%22%2C%20%22february%22%20%7D%0A%7D
In your case it will be:
https://localhost/path?clientId=2&date=2017-01-01&filters=%7B%0A%22clientId%22%3A%202%2C%0A%22date%22%3A%20%222017-01-01%22%2C%0A%22filters%22%3A%20%7B%0A%22days%22%3A%20%7B%20%22monday%22%2C%20%22tuesday%22%2C%20%22wednesday%22%20%7D%2C%0A%22months%22%3A%20%7B%20%22january%22%2C%20%22february%22%20%7D%0A%7D
You can use meyerweb.com to test encoding/decoding but in C# you can research HttpUtility.UrlEncode() method which can be used in your situation too.
If you really want to pass parameters in a query string, this is an example using ASP.NET MVC.
Create a route:
routes.MapRoute(
name: "Custom",
url: "{controller}/{action}/{clientId}/{date}/{filtersDay}/{filtersMonth}",
defaults: new { controller = "Home", action = "CustomQueryString" }
);
You can repeat an item and the Model Binding will create a string array:
http://localhost/Home/CustomQueryString?clientId=1&date=2017-01-01&filtersDay=Friday&filtersDay=Monday&filtersMonth=April&filtersMonth=June
and then, you will have this:
I have a ToDictionary extension method, that converts objects into the query string and you can pass it via RouteValues, I pass Model.SearchCriteria, which is a complex object in the folllowing example:
<a href='#Url.Action("ExportAll",
new RouteValueDictionary(Model.SearchCriteria))'>Export All</a>
ToDictionary is an extension method:
public static class ToDictionaryExtensionMethod
{
public static IDictionary<string, object> ToDictionary(this object source)
{
return source.ToDictionary<object>();
}
}
Unfortunately the following code doesn't work:
#Html.ActionLink("Export All", "ExportAll",
new RouteValueDictionary(Model.SearchCriteria.ToDictionary()),
new { #class = "btn btn-default" })
This is because this version of ActionLink accepts routevalues as an object, not as a RouteValueDictionary (in MVC 5). So to make it work, I have to convert the Html attributes to a dictionary as well which uses the correct overload of Html.ActionLink:
#Html.ActionLink("Export All", "ExportAll",
new RouteValueDictionary(Model.SearchCriteria.ToDictionary()),
new Dictionary<string,object>{{"class","btn btn-default"}})

DropDownListFor initial value not selected

I don't understand why the initial value is not selected when the form is loaded.
Here's my code
model.LUIsUsed = new List<SelectListItem>()
{
new SelectListItem { Value = "0", Text = "Ignore" },
new SelectListItem { Value = "1", Text = "Required" },
new SelectListItem { Value = "2", Text = "Optional" },
};
In my view
#Html.DropDownListFor(x => x.Foo[i].IsUsed, Model.LUIsUsed, new { #class= "form-control input-sm is-used" })
x.Foo[i].IsUsed value is "1", but required is not selected. I can't figure out why.
Is it because x.Foo is an array?
EDIT: When I don't use an array, it works
It looks like there's a problem with DropDownListFor inside a for loop.
I had to build a SelectList and specify the selected value.
#Html.DropDownListFor(x => x.Criterias[i].IsUsed, new SelectList(Model.LUIsUsed,"Value","Text", Model.Criterias[i].IsUsed))
It works, but I would like to know why.

Style dropdownlist i MVC [duplicate]

This question already has answers here:
#Html.DropDownListFor; How to set different background color for each item in DDL?
(2 answers)
Closed 8 years ago.
How do i go about to style each selectlistitem in my dropdownlist?
Can I give each item an id and access the in css?
Im trying to change the background-color of each item...
Here is the code:
#Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"},
},
"value",
"text",
2))
Html.DropDownListFor renders a , so I don't know why you're saying you're not using tags.
CSS does not care about server-side code, only rendered HTML, so if you're having issues then always show us the rendered HTML and your CSS.
Anyway, to style your element (and remember that because is a "replaced element" in CSS the opportunities for styling are limited, but you can do some cool things: http://bavotasan.com/2011/style-select-box-using-only-css/
You can override the id="" attribute of the so you can use the element selector in CSS, like so:
#Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"},
},
"value",
"text",
2), new { id = "mySelect" })
#mySelect { width: 135px; }
//or
#Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"},
},
"value",
"text",
2), new { class = "dropdown" })
However if you're using this DropDownListFor in a partial view then the id="" attribute won't be unique in the document, which is illegal. Try using different selectors that make use of the context, such as the descendant selector.
You shoud be able to use css pseudo-selectors, such as:
option:nth-child(1) {
background: red;
}

Categories