value not populating to kendo dropdown - asp.net-mvc-4

I have a MVC View with Kendo UI that binds value from a ListObject. When the data is fetched from xml file the Kendo Dropdown binds the value but the data is fetched from a table of a database its not binding the value to the dropdown. But the List which has values and returned to the bind function of Dropdown is haveing the values.
The values are binded in Json Format.
//Controller Code that returns value to Kendo Dropdown in View
public JsonResult BindTitles()
{
return Json(_title.GetTitle(), JsonRequestBehavior.AllowGet);
}
//Data Interface from Entity Framework
public partial interface ITitle
{
IList<tblTitle> GetTitle();
}
public IList<tblTitle> GetTitle()
{
List<tblTitle> tit = new List<tblTitle>();
tit = dbContext.GetTitle().ToList(); // Here the values are available in the "tit"
return tit;
}

Show the code of the view on which you configured your kendo dropdown. The controller code is not enough to give you the solution.

Related

Select dropdown value after post

I was hoping for some guidance on an issue I am having with preserving the value in a dropdownlist after post (razor)
I have a simple page:
#model testContingency.Models.ListByWardDD
#{
ViewBag.Title = "TestDropDowns";
}
<h2>TestDropDowns</h2>
<div>
#Html.DropDownList("HospModel", Model.Hospital, new { #onchange = "ChangeHospital(this.value)" })
#Html.DropDownList("WardModel", Model.Wards)
<script type="text/javascript">
function ChangeHospital(val) {
window.location.href = "/PatientListByWardDD/TestDropDowns?hospID=" + val;
}
</script>
</div>
here's the controller
public ActionResult TestDropDowns(int? hospID)
{
PASInpatientRepository pasRepo = new PASInpatientRepository();
var returnModel = new ListByWardDD();
var HospitalData = pasRepo.GetPatientHospitalsEnum();
returnModel.Hospital = pasRepo.GetHopspitalListItems(HospitalData);
var WardData = pasRepo .GetPatientWardsEnum(hospID);
returnModel.Wards = pasRepo.GetWardListItems(WardData);
ViewBag.HospSearch = hospID;
return View(returnModel);
}
In the controller PASInpatientRepository() communicates with a cache database. It passes back public IEnumerable < SelectListItem > GetHopspitalListItems. It calls stored procedures written within a cache database (same as sql stored procedures in essence). This is all working fine in its own crude way.
The issue I am having is that when I select the dropdownlist #Html.DropDownList("HospModel", Model.Hospital, new { #onchange = "ChangeHospital(this.value)" }) and the controller is called to refresh the Wards dropdown, I want to preserve the value I have selected in the hospital dropdown. I have tried a few different ways, but I admit, I'm a bit stuck. Most examples I found are for strongly typed.
As I mentioned, I'm new to MVC, but any advice on how to solve this issue, or suggestions on improving my code are greatly appreciated.
So I'm not sure what the Hospital property looks like but I'll make the assumption that each one has a unique ID.
Furthermore to bind the posted data to the view model you'll need to use forms in your view. To create the drop down list use the DropDownListFor-Helper. This way the data will be bound back to your Model after submitting the form.
So your view could look something like this
#model testContingency.Models.ListByWardDD
#{
ViewBag.Title = "TestDropDowns";
}
<h2>TestDropDowns</h2>
<div>
#using (Html.BeginForm("TestDropDowns", "YourController", FormMethod.Post))
{
#Html.DropDownListFor(x => x.HospitalID, Model.Hospital)
#Html.DropDownListFor(x => x.WardID, Model.Wards)
<input type="submit" value="send" />
}
</div>
Your ViewModel testContigency.Models.ListByWardDD must have at least the following properties
public class ListByWardDD {
public int HostpitalID { get;set; }
// the value of the SelectListItem-objects should be the hospital ID
public IEnumerable<SelectListItem> Hospital { get;set; }
public int WardID { get;set; }
// the value of the SelectListItem-objects should be the ward ID
public IEnumerable<SelectListItem> Wards { get;set; }
}
Once you post the form (for simplicity I added a button to send the form and left the javascript part out) the method TestDropDowns of your controller (which you need to fill in the BeginForm-Helper) will be called. That method expects expects an object of type ListByWardDD as a parameter and the framework will automatically populate the values for you.
[HttpPost]
public ActionResult TestDropDowns(ListByWardDD viewModel) {
// your code here, viewModel.HospitalID should contain the selected value
}
Note: After submitting the form the properties Hospital and Wards will be empty. If you need to display the form again, you need to repopulate those properties. Otherwise your dropdown lists are empty.
I tried my best to post valid code but I did not compile or test it.

Change WebGrid row color conditionally without Jquery/javascript ASP.NET MVC 4

I know this has been asked before but I wanted to ask it in my own way with more clarification. I am trying to conditionally set the background of a td that is created using a webGrid in ASP.NET MVC. I don't see a good way to do this.
So far what I have come up with is this:
grid.Column("DATT", header: "Date", format: (item) => new MvcHtmlString
(
(item.isCurrentlyBackordered)
?
"<div style=\"background-color: red\">Item Backordered</div>"
:
""
)),
This is an okay solution but I would like a more clean look because the webgrid default has a small padding in the table cell so the div won't expand completely to the size of the cell either.
Is there a way to edit the td in any way? I know I can change the background and other style attributes using jquery or javascript but I don't like the idea of having doing duplicate work to first build the table on the server, then on the client side iterate over it again conditionally changing the colors when this should have been completed with the first iteration.
Hope the following answer will help you
grid.GetHtml(columns: grid.Columns(grid.Column(columnName: "DATT", header: "Date",format: #<text> #{
if (#item.isCurrentlyBackordered)
{
<span>Item Backordered</span>
<script>
$("tr:contains('Item Backordered')").css("background-color", "yellow");
</script>
}
}</text>)))
Also you can write this in a common JQuery too
grid.Column("DATT", header: "Date", format: (item) => new MvcHtmlString
(
(item.isCurrentlyBackordered)
?
"<span>Item Backordered</span>"
:
""
)),
JQuery
<script type="text/javascript">
$(function () {
$("tr:contains('Item Backordered')").css("background-color", "yellow");
})
</script>
With the help of Golda's response and here
I was able to create an elegant solution. This solution uses JavaScript/JQuery, as it doesn't seem possible to do it without it but using (to me) a cleaner solution than what I had came across. What I did in the model class (type for List<>()) was add a property that refers to itself and returns an instance cast to its interface like so:
public iTrans This
{
get
{
return this;
}
}
I did this because the webGrid seems to only allow access to the properties and not methods; regardless of access level.
Then in that same model I have a method which will conditionally attach markup for a hidden input field to the data string and return it as an MvcHtmlString object:
public MvcHtmlString htmlColorWrapper(string cellStr, string hexColor = "#ccc")
{
if (isOnBackorder)
{
cellStr = cellStr + "<input type='hidden' class='color' value='" + hexColor + "'/>";
}
return new MvcHtmlString(cellStr);
}
And in the markup (partial view) I make my grid.Column call:
grid.Column("Date", header: "Date", format: (item) => item.This.htmlColorWrapper(item.Date.ToString("MM/dd/yyy"))),
Then I create the JavaScript function(s):
window.onload = function () {
SetFeaturedRow();
};
function SetFeaturedRow() {
$('.color').each(function (index, element) {
$(element).parent().parent().css('background-color', $(element).val());
});
}
The window.onload is needed to point to the SetFeaturedRow() function to set the row colors at page load, the function name, "SetFeaturedRow" is stored in the ajaxUpdateCallback property through the webgrid constructor arguments: new WebGrid(Model ..... ajaxUpdateCallback: "SetFeaturedRow"); Or it can be set through the WebGrid reference, ref.ajaxUpdateCallback = "SetFeatureRow"
This will be used during any ajax call the WebGrid class will make. So for example if there are multiple pages to the webgrid each selection is an ajax call and the row colors will need to be re-updated.
Hopefully this helps someone.

Binding Gridview with drop down list selection MVC 5

I have a drop down list (Cities) and on selection it should be able to bind a Grid View in MVC 5
i am able to bind the drop down list and grid view but unable to handle the select event of Drop Down list. I dont know how to proceed on this I dont want to use Jquery. Below is my code
// BELOW IS THE DROP DOWN LIST CODE
#using (Html.BeginForm("BindGridView", "FacebookConfig", FormMethod.Post, new { id = "Id" }))
{
#Html.DropDownList("Cities")
}
// ON SELECTION OF ABOVE I SHOULD BE ABLE TO BIND THE BELOW GRID VIEW
#if (Model != null)
{
foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.Keywords)
#Html.ActionLink("Edit", "Edit", new { id = item.Id })
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
// BELOW IS THE CODE IN CONTROLLER
public ActionResult Index()
{
var cities = So.BL.City.GetCities();
ViewBag.Cities = new SelectList(cities, "Id", "Name");
return View();
}
[HttpPost]
public ActionResult BindGridView(int id)
{
var filter = So.BL.FacebookFilter.SelectFBApprovalFilters(id);
return View(filter);
}
If you want to perform an operation on dropdown on change event you must go for javascript/jquery for handling the element events. To satisfy your requirement you may do as,
Create a <div> to hold the new grid view to be created with the id to select.
Create a partial view that generate the grid view.
Create a function either in jquery/javascript for dropdown list on change event.
From the function call an action method using ajax.
Create an action method which would do what ever the functionality you want to do and return the partial view with the model required for generating the grid view.
Finally on success method of ajax call, write the output response to the inner html of the <div>.
If definitely not going for jquery or javascript then do a post back and from the selected dropdown value in the post method fetch the data for grid view and bind it to the grid. Note here the form submission will not occur on dropdown selection must use a submit button. Also show the grid based Model if not null.
Choose which one you likely to adopt.

How to get a url after returning the view?

I am new to MVC4, I am using more then one form in one View. When i am posting the form i am getting all the formcollecion values in controller. When i am returning the different view also, its working fine. My problem is after returning view, the url showing that post method name.when i try to refresh this page its showing error.
Initially the url was : Admin/Activities
after posting the form : Admin/UpdateActivity
I need url like this after returning the view : Admin/Activities
how to get it, Please help me. Thanks in advance.
I dont have any separate view for this ActionResult. This is my code:
[HttpPost]
public ActionResult UpdateActivity(FormCollection coll)
{
................
ViewBag.updateAlert = "Activity updated sucessfully";
return View("Activities");
}
#using (Html.BeginForm("UpdateActivity", "Admin", FormMethod.Post,new { #id = "formID" }))
Change your form attribute as it. It will automatically return to the view Activities.
Note: if your form on Admin/Activities.
After updating the record,you can Redirect to that action,instead of returning the same view again, and instead of ViewBag you will have to use TempData as ViewBag will be null after redirecting:
[HttpPost]
public ActionResult UpdateActivity(FormCollection coll)
{
................
TempData["updateAlert"] = "Activity updated sucessfully";
return RedirectToAction("Activities","Admin");
}

Get all values from a listbox using Coded UI Test and select it

I am using uimap in coded ui test to get information about controlers in an application, the value returned for a listbox is "client" - controlType, technologyname MSAA and Name = session.
My goal is to be able to get all values of a listbox and then select a value using the code.
Is there a way to do that ?
Many thanks.
Given the UITestControl object for the list box you should be able to get all list entries by using the GetChildren method. It returns a collection having all the child controls of the parent control. Depending on the exact structure of your list box and its contents, you may need to call the method repeatedly to get the grandchild or deeper controls.
See http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.uitestcontrol.getchildren.aspx
Update
In C# you might write code based on the following:
foreach (UITestControl child in parent.GetChildren()) {
if ( someTestOfTheControl(child) ) {
... process the child control here ...
}
}
Or possibly on
foreach (UITestControl child in parent.GetChildren()) {
foreach (UITestControl grandChild in child.GetChildren()) {
if ( someTestOfTheControl(grandChild) ) {
... process the grandChild control here ...
}
}
}
Where someTestOfTheControl() tests whether the control is the one you are interested in.
Using UIMap - Get the control of ListBox
ItemToSelect - Is the name of item in string
WinList ListControl = new WinList(Control);
string[] CompleteList = ListControl.GetContent();
CompleteList = CompleteList.Where(x => x != null).ToArray();
string Value = CompleteList.First(x => x.Contains(ItemToSelect));
Mouse.Click((WinListItem)ListControl.Items.FirstOrDefault(x => x.Name.Contains(Value)));