I am new to MVC. I am trying for Cascading Dropdownlist in ASP.NET MVC 4. My problem is I want to access the selected countryid in #foreach loop
#Html.DropDownList("ddlCountry", new SelectList(#Model.Countries, "CountryId", "CountryName"))
$("#ddlCountry").change(function () {
#foreach (var item in #Model.States.Select(x=>x.countryId = ?))
{
}
});
How can I substitute countryId with the question mark above, so that I can filter the states
Thanks in Advance
Thanks
SRRIN
you can get the value in jquery by this
$("#ddlCountry option:selected").text();
As #Stephen said you cannot get the value of selected option using razor. Because the razor code is executed before page load.
A work around would be
$("#ddlCountry").change(function () {
var selectedVal= $("#ddlCountry option:selected").text();
var list = #Model.States.Tojson();
});
then use inArray for doing further operations
Thanks to all.
As Stephen and Nikitesh stated, javascript variable are not accessible inside razor scripts. So I succeeded with following approach.
var selectedCountryId = $("#ddlCountry").val();
var states = #Html.Raw(Json.Encode(Model.States));
for (var i = 0; i < states .length; i++) {
if (states [i].countryid == selectedCountryId ) {
... populate states here
}
}
Thanks
SRRIN
you can use dropdown selected value and pass in your query as:
#Html.DropDownList("ddlCountry", new SelectList(#Model.Countries,"CountryId", "CountryName"))
$("#ddlCountry").change(function () {
var countryId=parseInt($(this).val());
#foreach (var item in #Model.States.Select(x=>x.countryId = countryId))
{
}
});
Related
how find kendo tree view name or id on checkbox checked changed.
#(Html.Kendo().TreeView().Name("treeName")
.Checkboxes(c => c.Name("checkBoxes").CheckChildren(true))
.AutoScroll(true)
.Events(e => e.Check("onCheck"))
)
javascript code:
function onCheck(e) {
//how find tree name or id here??
}
First you must set you tree name if it is as you wrote "treeName" than it will look like this.
function onCheck(e) {
$("#treeName").getKendoTreeView().dataItem(e.node).id
}
Or you can search by UID
var treeviewName = $("#treeName").data("kendoTreeView");
var getitemByUid = treeviewName.dataSource.get();
treeview.findByUid(getitemByUid.uid);
var selectitemByUid = treeview.findByUid(getitemByUid.uid);
treeview.select(selectitemByUid);
I'm still fairly new to MVC and Razor and I'm hoping you can help me out with something. I am able to use the following code to just print the line (using #reply.GetProperty("PropertyName") but when I try to assign it to a variable (test) the code fails. Why is this and how can I get around it? I really need to be able to assign it and use it further in some other code.
#foreach (var reply in CurrentPage.Children)
{
#reply.GetProperty("PropertyName")
#{
string test = reply.GetProperty("PropertyName");
}
}
In your View
#{
string test = string.Empty;
}
#foreach (var reply in CurrentPage.Children)
{
#reply.GetProperty("PropertyName")
test = reply.GetProperty("PropertyName");
}
I have a ASP.NET MVC page with multiple forms on it, where each form edits a different instance of the same class. Each form also includes a Telerik DateTimePicker control. What I want is to have the element IDs change, but not the element name. So I have something like this:
string idString = string.Format("MyObject{0}", Model.ID)
#Html.Telerik().DatePickerFor(m => m.SomeDate).HtmlAttributes(new { id = idString + "-SomeDate" })
Now this works mostly fine, except that at the bottom of the page, the auto-generated Javascript that Telerik puts in looks like:
jQuery('#SomeDate').tDateTimePicker({
format:'M/d/yyyy h:mm tt',
minValue:new Date(1899,11,31,0,0,0,0),
maxValue:new Date(2100,0,1,0,0,0,0),
startTimeValue:new Date(2013,3,22,0,0,0,0),
endTimeValue:new Date(2013,3,22,0,0,0,0),
interval:30,
selectedValue:new Date(2013,3,22,11,9,1,180)
});
Note that my idString value didn't get put in. I can try:
#Html.Telerik().DatePickerFor(m => m.SomeDate).Name(idString + "SomeDate")
And this makes the auto-generated Javascript correct (jQuery('#MyObject123-SomeDate')) but now the element name is wrong, so TryUpdateModel fails.
How can I get this to work? Thanks.
EDIT: I hacked this using the following Javascript, but this is a kludgy way to fix this.
$(function () {
window.setTimeout(function () {
for (var i = 0; i < document.getElementsByTagName("input").length; i++) {
var obj = document.getElementsByTagName("input")[i];
if (obj.id.indexOf("SomeDate") == -1)
continue;
obj.name = "SomeDate";
}
}, 150)
});
The solution was to use the Telerik object's .InputHtmlAttributes method.
#Html.Telerik().DatePickerFor(m => m.SomeDate).InputHtmlAttributes(new { id = idString + "-SomeDate" })
Hi i need to show a list of data using viewbag.but i am not able to do it.
Please Help me..
I tried this thing:
ICollection<Learner> list = new HobbyHomeService().FetchLearner();
ICollection<Person> personlist = new HobbyHomeService().FetchPerson(list);
ViewBag.data = personlist;
and inside view:
<td>#ViewBag.data.First().FirstName</td>
But this does not show up the value and gives error saying "Model.Person doesnot contain a defibition for First()"
In your view, you have to cast it back to the original type. Without the cast, it's just an object.
<td>#((ViewBag.data as ICollection<Person>).First().FirstName)</td>
ViewBag is a C# 4 dynamic type. Entities returned from it are also dynamic unless cast. However, extension methods like .First() and all the other Linq ones do not work with dynamics.
Edit - to address the comment:
If you want to display the whole list, it's as simple as this:
<ul>
#foreach (var person in ViewBag.data)
{
<li>#person.FirstName</li>
}
</ul>
Extension methods like .First() won't work, but this will.
To put it all together, this is what it should look like:
In the controller:
List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;
Then in the view:
#foreach (var item in ViewBag.Funds)
{
<span> #item.FundName </span>
}
simply using Viewbag data as IEnumerable<> list
#{
var getlist= ViewBag.Listdata as IEnumerable<myproject.models.listmodel>;
foreach (var item in getlist){ //using foreach
<span>item .name</span>
}
}
//---------or just write name inside the getlist
<span>getlist[0].name</span>
i had the same problem and i search and search .. but got no result.
so i put my brain in over drive. and i came up with the below solution.
try this in the View Page
at the head of the page add this code
#{
var Lst = ViewBag.data as IEnumerable<MyProject.Models.Person>;
}
to display the particular attribute use the below code
#Lst.FirstOrDefault().FirstName
in your case use below code.
<td>#Lst.FirstOrDefault().FirstName </td>
Hope this helps...
Use as variable to cast the Viewbag data to your desired class in view.
#{
IEnumerable<WebApplication1.Models.Person> personlist = ViewBag.data as
IEnumerable<WebApplication1.Models.Person>;
// You may need to write WebApplication.Models.Person where WebApplication.Models is
the namespace name where the Person class is defined. It is required so that view
can know about the class Person.
}
In view write this
<td>
#(personlist.FirstOrDefault().Name)
</td>
Just put a
List<Person>
into the ViewBag and in the View cast it back to List
This is what i did and It worked...
C#
ViewBag.DisplaylList = listData;
javascript
var dispalyList= #Html.Raw(Json.Encode(this.ViewBag.DisplaylList));
for(var i=0;i<dispalyList.length; i++){
var row = dispalyList[i];
..............
..............
}
//controller You can use this way
public ActionResult Index()
{
List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;
return View();
}
<--View ; You can use this way html-->
#foreach (var item in (List<Fund>)ViewBag.Funds)
{
<p>#item.firtname</p>
}
I had the problem that I wanted to use my ViewBag to send a list of elements through a RenderPartial as the object, and to this you have to do the cast first, I had to cast the ViewBag in the controller and in the View too.
In the Controller:
ViewBag.visitList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)
visitaRepo.ObtenerLista().Where(m => m.Id_Contacto == id).ToList()
In the View:
List<CLIENTES_VIP_DB.VISITAS.VISITA> VisitaList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)ViewBag.visitList ;
I want to show a poll result for a specific poll question.
When question list clicked i want to bind my chart with a query according to selected questionId.
So my plan was;
1. get questionId from selected question row. it's ok.
defining ClientEvents.OndataBinding event on my chart. So i would be able to
pass questionId with;
function onChartDataBinding(e) {
e.data = $.extend(e.data, { questionId: questionId });
}
using $('#ChartPollResults').data('tChart').rebind(); on question list grid row selected event.
This scenario works when i have second grid binding according to first grids selected row.
But it seems there is no ClientEvents.OnDataBinding event on chart control.
And "rebind()" method isn't supported on Chart control.
The chart conrol i use is below.
#(Html.Telerik().Chart<QuestionResult>()
.Theme("WebBlue")
.Name("ChartPollResults")
.Title("Poll Question Choice Number vs. Choice Count")
.Legend(legend => legend.Position(ChartLegendPosition.Bottom))
.Series(series =>
{
series.Bar("ChoseCount").Name("Choice Count").Gap(5);
})
.CategoryAxis(axis => axis.Categories(o => o.ChoiceNumber))
.DataBinding(dataBinding => dataBinding.Ajax().Select("_PollResultChartBinding", "Poll", new { questionId = 0 }))
.HtmlAttributes(new { style = "width: %100px; height: 270px" })
)
My Controller binding method;
public ActionResult _PollResultChartBinding(int questionId = 0)
{
//questionId = 3;
if (!ModelState.IsValid || questionId == 0)
return Json(new List<QuestionResult>());
PollQuestionDefinition pollQuestion = service.Get(questionId);
List<PollAnswer> pollAnswers = service.GetPollAnswersByQuestion(questionId);
PollQuestionResultUI result = new PollQuestionResultUI(pollQuestion, pollAnswers);
return Json(result.Results);
}
When i comment out //questionId = 3; line i can see the results for the question wiht Id= 3 in chart with no problem.
But i can't pass questionId to chart.
Thanks in advance.
This is my Opinion for your source code should be like this:
//controller binding method
public ActionResult _PollResultChartBinding(string questionId)
{
//questionId = 3;
int _questionId = String.IsNullOrEmpty(questionId) ? 0 : Convert.ToInt32(questionId);
if (_questionId == 0)
return Json(new List<QuestionResult>());
PollQuestionDefinition pollQuestion = service.Get(_questionId);
List<PollAnswer> pollAnswers = service.GetPollAnswersByQuestion(_questionId );
PollQuestionResultUI result = new PollQuestionResultUI(pollQuestion, pollAnswers);
return Json(result.Results);
}
**in your view, there is no problem with the code**.
but, for rebind that chart, this is the code :
example : (running from developer console for IE or firebug for firefox browser)
var chartPollResult = $('#ChartPollResults').data('tChart');
chartPollResult.rebind({ questionId: "0"});
but if you want make it into function, code should be like this:
function rebindChartPollResult(e, param) {
e.data('tChart').rebind({ questionId: param});
}
calling method :
rebindChartPollResult($('#ChartPollResults'), "0");
reference for telerik chart ajax binding (not included how to rebind chart) :
http://demos.telerik.com/aspnet-mvc/chart/ajaxbinding
First of all, one thing I immediately noticed is that you set questionId equal to 0 in your ActionResult parameters. I actually just modified a Chart I had up and running to pass in
new { questionID = 0}
as an additional parameter to my Ajax select statement and it passed in fine.
As for passing the parameter you could consider using a POST to the server on Grid selection and pass the parameter that way. I know it might not be ideal here, but you could theoretically either populate the Chart in that post, or just set a ViewData entry to contain the particular questionID that you are looking for.
I also noticed that you submitted this to the Telerik forums and from the response there it would seem that the above approach might actually work pretty well, or you could use the approach mentioned there (partial view with ajax calls).