How to Pass Kendo DropDownList DataTextField value to Controller - asp.net-mvc

I have a Kendo DropDownList on the View and I want to pass its DataTextField value to the Controller and then pass and them on the labels in another View. Although I can pass DataValueField values to the Controller, I cannot pass DataTextField values. I tried to apply different scenarios but I could not. Any idea? On the other hand, if it is not possible, should the DataTextField values be populated again on the Controller and return to the other View?
View:
#model IssueViewModel
...
#Html.LabelFor(m => m.ProjectID)
#(Html.Kendo().DropDownList()
.Name("ProjectID")
.DataTextField("ProjectName")
.DataValueField("ProjectId")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProjects", "Issue");
});
})
)
Controller:
public JsonResult GetProjects()
{
var projects = repository.Projects;
return Json(projects.Select(m => new { ProjectId = m.ID, ProjectName = m.Description }), JsonRequestBehavior.AllowGet);
}
/* I want to pass the DataTextField values to this
method and return them to the CreateManagement view */
public ActionResult Create(IssueViewModel issueViewModel)
{
return RedirectToAction("CreateManagement", issueViewModel);
}

Change your controller to this:
public JsonResult GetProjects()
{
var projects = repository.Projects;
return Json(projects.Select(m => new SelectListItem { ProjectId = m.Description, ProjectName = m.Description }).ToList(), JsonRequestBehavior.AllowGet);
}
Since the DropDownList uses DataTextField for the user and uses DataValueField for the server communications, so you have to use DataTextField value for both. Then you can use it for the next operations.
Edit: if you need both values on the controller, change JsonResult method to :
return Json(projects.Select(m => new SelectListItem { ProjectId = m.Description + "," + m.ID , ProjectName = m.Description }).ToList(), JsonRequestBehavior.AllowGet);
Now you can use both in the next operations just by spiting them like:
var _both = value.split(',');//value: returned value from the view

Related

ASP MVC DropDownList has extra value ( the integer id )

I end up with three values in my DropDown... Two expected values and an additional value that is the primary key of the selecteditem, ie. "2"
How do I get rid of the "2", and still select the appropriate item?
#Html.DropDownListFor(x => x.ComicBookId, ComicNet.Models.ComicBook.GetValues(), Model.ComicBookId.ToString(), new { #id = "ComicBookId" })
public partial class ComicBook
{
public static SelectList GetValues()
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
SelectList selectList = new SelectList(db.ComicBooks.ToList(), "ComicBookId", "Name");
return selectList;
}
}
}
Simply remove the third parameter as it is setting the optionLabel:
#Html.DropDownListFor(x => x.ComicBookId, ComicNet.Models.ComicBook.GetValues(), new { #id = "ComicBookId" })
This is the overload that you're using: SelectExtensions.DropDownListFor Method (HtmlHelper, Expression>, IEnumerable, String, Object)
Here's the one you want: SelectExtensions.DropDownListFor Method (HtmlHelper, Expression>, IEnumerable, Object)

Retrieve all drop-down values from database and show the saved value as selected one in drop down

I am using a kendo grid with pop up editing mode and editor template in mvc4. The template consists of a drop down list which is bound through database. The problem comes when in Edit operation all other data is retrieved along with all elements of drop down list and displayed in respective html attributes such a textbox ,checkbox etc but the value which i have saved from drop down list is not shown auto selected there.
Example
During add operation i have selected "Work" from the drop down list and saved it in database. At the time of Edit i want "Work" to be shown auto selected in drop down list.
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Update([DataSourceRequest] DataSourceRequest request,Model object)
{
if (obj == null || !ModelState.IsValid) return null;
var obj = _Repo.FindBy(t => t.ID == object.ID);
obj.Text = object.Text;
obj.Type = object.Type;
obj.MasterTypeID_Fk = new Guid(object.Type);
obj.Notes = object.Notes;
obj.Primary = object.Primary;
obj.LastVerified = DateTime.Now.ToUniversalTime();
obj.LastUpdated = DateTime.Now.ToUniversalTime();
_Repo.Update(obj);
var result = new[] { object }.ToDataSourceResult(request, ModelState);
return Json(result);
}
//this is my code for ddl in editor template
#(Html.Kendo().DropDownList()
.Name("Type")
.DataTextField("Value")
.DataValueField("TypeID")
.DataSource(source =>
{
source.Read(read => { read.Action("GetTypes", "Dashboard"); });
})
)
// this is code in controller to bind ddl
public ActionResult GetTypes()
{
List<TypeModel> Type = _Repo.GetTypes().ToList().ToMap<TypeBO, TypeModel>();
Type.Insert(0, new TypeModel() { Value = "--Select--", TypeID = Guid.Empty });
return Json(Type, JsonRequestBehavior.AllowGet);
}
You can set your value in Html helper using Value("ValueData"):
#(Html.Kendo().DropDownList()
.Name("Type")
.DataTextField("Value")
.DataValueField("TypeID")
.DataSource(source =>
{
source.Read(read => { read.Action("GetTypes", "Dashboard"); });
})
.Value("ValueData")
)
Like in this example: http://demos.telerik.com/aspnet-mvc/dropdownlist/index

MVC dropdownlist : Setting the value and text based upon table in database

I have a table in database
I've been able to show the list of TypeName in my dropdownlist in my View
Currently i'm doing this is my controller
[HttpGet]
public ActionResult CreateModule()
{
var moduleTypes = _db.ModuleTypes.Select(moduleType => moduleType.TypeName).ToList();
var model = new CreateModule
{
TypeNames = moduleTypes.Select(m => new SelectListItem
{
Value = m,
Text = m,
})
};
return View(model);
}
and in view
<div class ="input-block-level">#Html.DropDownListFor(model => model.SelectedModuleTypeName, Model.TypeNames)</div>
That results to something like this
based upon my code, I'll get the TypeName from the view in my controller's post method.
How I can I change my code in order to access Id of the TypeName in controller?
Modify your Action:
public ActionResult CreateModule()
{
var moduleTypes = _db.ModuleTypes.Select(moduleType => new { TypeName = moduleType.TypeName, Id = moduleType.Id }).ToList();
var model = new CreateModule
{
TypeNames = moduleTypes.Select(m => new SelectListItem
{
Value = m.Id.ToString(),
Text = m.TypeName,
})
};
return View(model);
}
Select multiple items instead of single
var moduleTypes = _db.ModuleTypes
.Select(
moduleType => new {
Id = moduleType.Id
TypeName = moduleType.TypeName}
).ToList();
var model = new CreateModule
{
TypeNames = moduleTypes.Select(m => new SelectListItem
{
Value = m.Id.ToString(),
Text = m.TypeName,
})
};
The first statement is creating anonymous object using linq, and second statement is using it to create CreateModule

accessing viewbag in the view

net MVC. I have assigned a list of objects to the viewbag property can anyone please tell me as to how i can get the list in the view to use it in the drop down list? here is my controller code & view code
Controller:
public ActionResult GetSection(int sectionId,int contactId)
{
ContactDetailSectionModel contactDetailSection = new ContactDetailSectionModel { SectionId = sectionId,ContactId=contactId };
contactDetailSection.FetchAllSubsections();
ContactDetailSectionModel customSections = new ContactDetailSectionModel();
customSections.FetchCustomSubSections();
if(customSections != null && customSections.ContactDetailSubSections != null)
{
ViewBag.CustomSubSections = customSections.ContactDetailSubSections;
}
return PartialView("~/Views/Contacts/Details/EditSection.cshtml", contactDetailSection);
}
View Code:
#Html.DropDownListFor(m => m.ContactDetailSubSections[1], new SelectList(ViewBag.CustomSubSections , "Name", "Name",Model.ContactDetailSubSections[1].Name))
#Html.TextAreaFor(m => m.ContactDetailSubSections[1].Text)
I think the first parameter in your #Html.DropDownlist should be string or some scalar quantity it cannot be a collection.

Problem with DropDownListFor SelectedItem

This has totally puzzled me.
Here's my View:
#Html.DropDownListFor(model => model.ScoreDescription,
Model.RatingOptions,
"--",
new { #id = clientId })
And the model:
public decimal? Score { get; set; }
public SelectList RatingOptions
{
get
{
var options = new List<SelectListItem>();
for (var i = 1; i <= 5; i++)
{
options.Add(new SelectListItem
{
Selected = Score.HasValue && Score.Value == Convert.ToDecimal(i),
Text = ((decimal)i).ToRatingDescription(ScoreFactorType),
Value = i.ToString()
});
}
var selectList = new SelectList(options, "Value", "Text");
// At this point, "options" has an item with "Selected" to true.
// Also, the underlying "MultiSelectList" also has it.
// Yet selectList.SelectedValue is null. WTF?
return selectList;
}
}
As the comments suggest, i can't get the selected value to happen.
Is it something to do with the fact i'm using a nullable decimal ? After that loop, options is correct in that it has exactly 1 item with select to true, so it seems i'm doing the right thing.
Now, if i use a different SelectList overload:
var selectedValue = Score.HasValue ? Score.Value.ToString("0") : string.Empty;
var selectList = new SelectList(options, "Value", "Text", selectedValue);
It works. Why? At first i thought it might be a LINQ-trick (e.g deferred execution), but i tried forcing a .ToList() and there is no difference.
It's like setting the Selected property as you create the SelectListItem has no effect, and you have you set it at the end using the SelectList ctor parameter.
Can anyone shed some light on this?
If you look at the implementation of the SelectList class it never actually uses the fact that you are passing a SelectListItem. It works with an IEnumerable. So the Selected property of a SelectListItem is not used. Personally I prefer setting the selected value of a dropdown by setting the value of the corresponding property that you are binding the ddl to.
Example:
public int? Score { get; set; }
public SelectList RatingOptions
{
get
{
var options = Enumerable.Range(1, 5).Select(i => new SelectListItem
{
Text = ((decimal)i).ToRatingDescription(ScoreFactorType),
Value = ((decimal)i).ToString()
});
return new SelectList(options, "Value", "Text");
}
}
and then in the controller action simply set the Score property to the necessary value and in the view use this Score property to bind to:
#Html.DropDownListFor(
model => model.Score,
Model.RatingOptions,
"--",
new { #id = clientId }
)

Resources