Filtering Dropdown list in mvc razor view - asp.net-mvc-3

I've two tables
1.Country
ID
CountryName
and other table is
2.State
State ID
State Name
Country Id
I am using this code to populate data in dropdownlist of country in citycontroller.cs
ViewBag.countries = new SelectList(db.Couns.OrderBy(c => c.CountryName).ToList(), "ID", "CountryName");
in create.cshtml
#Html.DropDownList("Select Country", ViewBag.countries as SelectList)
i want the functionality in which the state dropdown should be populated according to the selection of the country dropdown what should be done?????

If you have the list of states downloaded already to the client machine then knockout.js would be the way to go. If you want to download only the states that are related to the selected country once that selection is made you shohuld make an AJAX call to the server when a country is selected and have the success function populate the state list.

You will need to use Ajax calls for that. You may want to have a look at this answer I provided to a question similar to yours.

You can wse jQuery ajax to load the States when the country gets selected.
<script type="text/javascript">
$(function(){
$("#Country").change(function(){
var states="";
var countryId=$(this).val();
$.getJSON("#Url.Action("GetStates","Home")/"+countryId,function(data){
$.each(data,function(index,item){
states+="<option value='"+item.ID+"'>"+item.StateName+"</option>";
});
$("#States").html(states);
});
});
});
</script>
Assuming Country is the ID of your Country DropDown and States is the ID of your States Dropdow and you have an action method which accepts the country id as the parameter and get the states in JSON format
public ActionResult GetStates(int id)
{
var stateList=repo.GetStatesForCountry(id);
return Json(stateList,JsonRequestBehaviour.AllowGet);
}
Assuming repo.GetStatesForCountry returns a List of States based on the country Id passed. You may replace that function call with your method call which returns a list of State class objects.
Suggestion : I would try to avoid the dynamic ViewBag /ViewData approach to populate the Dropdwon and switch to a more strongly typed approach. Here is an example how to do it.

Related

how to get selected value for Kendo DropDownList

I can't figure out how to determine which item is selected in the my kendo dropdownlist. My view defines it's model as:
#model KendoApp.Models.SelectorViewModel
The ViewModel is defined as:
public class SelectorViewModel
{
//I want to set this to the selected item in the view
//And use it to set the initial item in the DropDownList
public int EncSelected { get; set; }
//contains the list if items for the DropDownList
//SelectionTypes contains an ID and Description
public IEnumerable<SelectionTypes> ENCTypes
}
and in My view I have:
#(Html.Kendo().DropDownList()
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This DropDownList contains the values I expect but I need to pass the selected value back to my controller when the user clicks the submit button. Everything works fine except I don't have access to which item was selected from the controller's [HttpPost] action. So, how do i assign the DropDownList's value to a hidden form field so it will be available to the controller?
For anyone who found this wondering how to get the selected value in JavaScript, this is the correct answer:
$("#EncounterTypes").data("kendoDropDownList").value();
From the documentation: http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#methods-value
when select a value from a dropdown list, and in the selec event , we can get the selected value as following ,
#(Html.Kendo().DropDownList()
.Name("booksDropDown")
.HtmlAttributes(new { style = "width:37%" })
.DataTextField("BookName")
.DataValueField("BookId")
.Events(x => x.Select("onSelectBookValue"))
.DataSource(datasource => datasource.Read(action => action.Action("ReadBookDropDow", "PlanningBook").Type(HttpVerbs.Get)))
.OptionLabel("Select"))
javascript function like following ,
function onSelectBookValue(e) {
var dataItem = this.dataItem(e.item.index());
var bookId = dataItem.BookId;
//other user code
}
I believe this will help someone
Thanks
Hello I was just going through this problem,kept on searching for 2 hours and came up with a solution of my own.
So here is the line to fetch any data bidden to the kendo drop down.
$("#customers").data("kendoDropDownList").dataSource._data[$("#customers").data("kendoDropDownList").selectedIndex].colour;
Just change the id customers to the id you have given tot he kendo drop down.
Maybe you should be using the DropDownListFor construct of the Kendo DropDownList like so in your view:
#(Html.Kendo().DropDownListFor(m => m.EncSelected)
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This way, when you submit, it will be availble on the POST request and you won't need to put an hidden field anywhere.
BUT should you need to use the hidden field for some reason, put it there, subscribe the the select event of the dropdown list and put using JQuery (for instance) put the selected item on the hidden field.
It's your choice :)
If you want to read also out the text of the dropdown, you can get or set the value by using the following kendo function:
$('#EncounterTypes').data("kendoDropDownList").text();
REFERENCE TO THE DOCUMENTATION
Using this .val() as #Vivek Parekh mentions will not work - there is no function .val() in the kendo framework.
If you want you could use jQuery and get the value back: $('#EncounterTypes').val()
Updated DEMO
$("#EncounterTypes").kendoDropDownList().val();
You can get the selected item like following code and then use item.property to get further information
var selectedFooType = $("#fooType").data("kendoDropDownList").dataItem();
selectedFooType.name
//OR
selectedFooType.id

Proper way for delete function in ASP.NET MVC 4 WebGrid

I just started using WebGrid and I have been searching a proper way to delete a row.
But I don't want to use solutions which redirects the user an other window. I just want that when the user clicks delete then pop up a confirm window and if the user choose yes, delete the data and refresh the page, but with ajax.
I have found a way to do this, but I have not seen other people do it on the Internet in the same way and I want to know if it is a good practice to follow it in the future.
In the WebGrid I have the following column definition:
grid.Column(header: "", format: #<text> <button type="submit" name="Delete" value="#item.Id">Delete</button></text>)
It is in a #Ajax.Beginform(...) { ... }
In my Controller I check if a Delete button was clicked and get the Id this way:
[HttpPost]
public ActionResult Index(ManageOvertimesViewModel model, FormCollection formCollection)
{
...
if (formCollection["Delete"] != null)
{
int id = int.Parse(formCollection["Delete"]);
//Delete the data
return PartialView("IndexPartial", model);
}
...
}
When I delete something in this view other data displayed can be changed, so I need to have the posted ViewModel to recreate some DropDowns in the view and this is the reason I don't use Ajax.ActionLink to solve the delete.
So is it a good way to achieve delete?
Here you have example from View:
grid.Column("", "", canSort: false, format:#<b>#Html.ActionLink("Delete", "DeletePrizeRun", new { id = item.ID })</b>, style: "column")
Here code from controller:
public ActionResult DeletePrizeRun(int id)
{
using (var context = new ExampleDataContext())
{
var prizeRun = context.PrizeRuns.FirstOrDefault(p => p.id == id);
context.PrizeRuns.Remove(prizeRun);
context.SaveChanges();
}
}
For your solution the Grid has to be inside the the Ajax form. The ajax form will do partial updates and the grid will do (if you specify an ajax target which you must if you want to avoid page reloads, at least if you are using paging and sorting with pager / sort headers generated by WebGrid). That is where my headache with a similar solution started. The Grid started to behave strangely when sorting or paging, e.g. the controller was executed multiple times.
I ended up giving up on WebGrid and I am now using html tables with razor commands which works great and provides much better control.
I recommend not to use WebGrid for anything but the most simple demo.
Other than that I see no problem with your approach, using name / value to pass data to the controller worked for me.

Assign default values while creating new Item

This question about Telerik MVC Grid.
I have two Grids with Master->Details relationship. These to grids are loaded using Ajax Binding. I want to create new Item in Details grid and pass ProductId field value from Master grid.
I have added property below but do not know how to get ProductId from Master grid. I have tried to pass value using ViewBag on Detail child loading it it seems ViewBag is not assigned then Ajax call is performed. Maybe someone know how to solve this problem?
Editable(editing => editing.DefaultDataItem(new UserViewModel { ProductId = ?????? })
When you have Master Grid and Detail Grid,
and you want to create record in the Detail Grid ,
You should add JavaScript logic which uses the OnSave event of the Detail Grid to pass additional value to the server (it should be the selected record in the Master Grid).
Check the documentation there are examples.
Have you tried using client side template for this?
Editable(editing => editing.DefaultDataItem(new UserViewModel { ProductId = <#= ProductId #> })
If you're using Ajax binding, you could also pass the parent's ID on insert:
dataBinding.Ajax().Insert("_Insert", "SubItem", new { productId= "<#= ProductId #>" }));
Don't forget to set your DataKey of the parent grid
.DataKeys(keys => keys.Add(c => c.Id))

How to save checkbox checked values in Database [duplicate]

I have a simple mvc project consisting of one table named Persons and that table has some attributes like name, age, surname and so on.
I Recently added an attribute to table which is type of bit in SQL and bool in C# and for me it represents some status. If it is ok I put that status to true or false.
In one controller I create an index view of my Persons in the database and I display the status as a checkbox. That is working ok. What I want to do is to change the status if I click on that checkbox instead of using an edit view for all of the atributes.
I just want to save checkbox value from my index view to database.
Some people advised me to create an action in my controller like so:
public ActionResult Save(int id, bool status){}
Where id is id of my person in db and status is a value of the checkbox I clicked.
So how do I call that function with jquery, ajax or javascript and send those params?
I am not so good with ajax and a little bit afraid of it :)
And one more thing I manage to show checkbox value corectly from my databse only in this way:
#Html.CheckBox("somename", item.Status)
<input name="somename" type="hidden" value="false"/>
Any help or advice or sending me to good direction is good!
You have several options. One way would be to place the checkboxes in a (normal) form and then use the jQuery Form plugin to Ajaxify the form:
#using(Html.BeginForm()) {
#Html.Checkbox(...)
}
<script type="text/javascript">
$(document).ready(function () {
$('form').ajaxForm({
success: Saved,
error: HandleError
});
});
function Error(response, status, err) {
// code to handle error here
}
function Saved(responseText, statusText, xhr, $form) {
// code to handle succes, if any
}
</script>
You could, of course, use an #Ajax.BeginForm as well, but this has the advantage of being easily downgradable. Just remove the jQuery form initialisation and you got yourself a regular form : )
Another possibility is to simply use an #Ajax.ActionLink. I wrote a blog post on how to deal with Ajax.ActionLink that I think will help you out.
The signature for your controller action on your question looks correct:
public ActionResult Save(int id, bool status){}
Another options is actually to create a Settings view model (call it what you will), and in there just have a bunch of bool properties to represent the checkboxes:
public class Settings
{
public bool Status { get; set; }
// more properties here
}
then you can bind your action to the Settings object:
public ActionResult Save(int id, Settings settings){}
This will come in handy in case you end up having multiple checkboxes to bind.

how to retrieve value of dropdown selection when form is not been submitted yet

I have following code
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.IDs, new SelectList(Model. IDs), Model.SelectedID)
}
So user selection from this combo bind to SelectedID property of the model. My understanding is that this binding happen only when form is submitted. Let’s say from the same page, I need to do an AJAX call but at this point ) Model.SelectedID does not provide any value because form hasn’t been submitted yet (although user has selected something from drop down). Any ideas how to best deal with this situation?
You can use javascript.
var selectedValue = $("#IDs").val();
bind a change event to your DD
$("#DDL_ID").change(function(){
var currVal = $(this).val();
//do ajax
});
As others have pointed you would get this value with javascript on the change of the drop down list.
I wanted to point out however, that your understanding of the overload you are using for the drop down list is incorrect. This overload will display a default option box label.
For example you could prompt the users to select select something from the list:
#Html.DropDownListFor(m => m.IDs, new SelectList(Model. IDs), "Select Something...")
If you were to post the form in your example as is, you can see the selected item come across in the form. If your view model is setup in such a fashion the model binder would take over and bind this value to your "SelectedID" property.
[HttpPost]
public string DropDown(FormCollection form)
{
var selectedItem = form["IDs"];
return selectedItem;
}

Resources