Html.DropDownListFor will ignore ViewBag values - asp.net-mvc-4

I have the following action method:-
public ActionResult AdvanceSearch(string AssetTypeName)
{
ViewBag.Techtypes = repository.GetAllTechnologyType().ToList();
ViewBag.AssetID = repository.GetTechnologyTypeID(AssetTypeName);
return View();
}
which will call the folloiwng view :-
//code goes here
#Html.DropDownListFor(model =>model.AssetTypeID, ((IEnumerable<TMS.Models.TechnologyType>)ViewBag.Techtypes).Select(option => new SelectListItem {
Text = (option == null ? "None" :option.Name),
Value = option.AssetTypeID.ToString(),
Selected = (Model != null) && (option.AssetTypeID == ViewBag.AssetID)
}), "All")
//code goes here
but the drop down will always show the default value"All" , instead of selecting the item that match the viewBag value option.AssetTypeID == ViewBag.AssetID. baring in ming that the ViewBag will have the correct value. can anyone adice what might be the problem ?
Thanks

I think your condition is wrong. Try this. Check the 'Selected' property.
#Html.DropDownListFor(model => model.AssetTypeID, ((IEnumerable<TechnologyType>)ViewBag.Techtypes).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Name),
Value = option.AssetTypeID.ToString(),
Selected = (option.AssetTypeID == (int)ViewBag.AssetID)
}), "All")

Related

Copy cart into another cart in order to change the id_cart

I would like to give the cart object a new id, I have the following code:
if ($payment->order_result->return->failures->failure == 'field.ordernumber.exists') {
$dup = $this->context->cart->duplicate();
$this->context->cart->delete();
$this->context->cart = new Cart($dup['cart']->id);
}
The cart isn’t “replaced”, I tried several things: use the $GLOBALS of global keyword, but nothing really replaces or changes the cart object. What is the best approach?
Try with :
if ($payment->order_result->return->failures->failure == 'field.ordernumber.exists') {
$context = Context::getContext();
$cart_products = $context->cart->getProducts();
$this->context->cart->delete();
$newCart = new Cart();
if (!$context->cart->id) {
$guest = new Guest();
$context->cart->mobile_theme = $guest->mobile_theme;
$context->cart->add();
if ($context->cart->id)
$context->cookie->id_cart = (int)$context->cart->id;
}
foreach ($cart_products as $product) {
Db::getInstance()->insert('cart_product', array(
'id_product' => (int)$product->id,
'id_product_attribute' => (int)0,
'id_cart' => (int)$newCart->id,
'quantity' => (int)$product->quantity,
'date_add' => date('Y-m-d H:i:s')
));
}
}
Inspired by the answer of #ethercreation, I changed the following to solve my problem:
From
$dup = $this->context->cart->duplicate();
$this->context->cart->delete();
$this->context->cart = new Cart($dup['cart']->id);
To
$dup = $this->context->cart->duplicate();
$this->context->cart->delete();
$this->context->cookie->id_cart = $dup['cart']->id;
The essential part is $this->context->cart cannot be changed. The cart needs to be copied, then the current cart in the cookie should be changed. Therefore the cookie $this->context->cookie->id_cart should be changed to the id_cart of the newly created cart!

Using system.linq.lookup values for dropdownfor mvc 4

In MVC 4 I am using razor to get items from collection and assign it to a var. The var is of type
{System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping}
This is my code
var ChairList = Model.Interviewers.Where(d => d.LocKey == Convert.ToString(location.LocationKey) && d.IsChair && d.Date == date.Date).GroupBy(x => new { x.FullDetails, x.InterviewerId, x.Preference }).ToList();
And how it looks in watch:
- ChairList Count = 1 System.Collections.Generic.List<System.Linq.IGrouping<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>>
- [0] {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping} System.Linq.IGrouping<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer> {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping}
+ [System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping] {System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping} System.Linq.Lookup<<>f__AnonymousType0<string,System.Guid,string>,IMEModels.InterviewManagement.Interviewer>.Grouping
- Key { FullDetails = "TEST - Richard Jackson - (80020937)", InterviewerId = {ff1efad7-7176-4fab-a1bb-30f6656c8880}, Preference = "Available" } <Anonymous Type>
FullDetails "TEST - Richard Jackson - (80020937)" string
+ InterviewerId {ff1efad7-7176-4fab-a1bb-30f6656c8880} System.Guid
Preference "Available" string
+ Raw View
I want to use this for a dropdownfor but it doesn't recognise the key and value that I am giving for it:
#Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId, new SelectList(ChairList, "InterviewerId", "FullDetails"))
Can someone help me with this piece of code? It's possible that there is an easier way of doing this that I am unaware of.
For view
#Html.DropDownListFor(m => m.InterviewSchedules[location.InterviewDates.IndexOf(date)].ChairId,, ViewData["ReturnList"] as SelectList, new { #class = "form-control" })
For Code (Return as viewData)
public SelectList ReturnList(Guid UID) {
var ChairList = Model.Interviewers.Where(d => d.LocKey == Convert.ToString(location.LocationKey) && d.IsChair && d.Date == date.Date).GroupBy(x => new { x.FullDetails, x.InterviewerId, x.Preference }).ToList();
List<SelectListItem> selectItems = ChairList.Select(s => new SelectListItem() {
Text =FullDetails,
Value = InterviewerId.ToString(),
Selected = false
}
).ToList();
selectItems.Insert(0, new SelectListItem() {
Text = " --Select -- ",
Value = null,
Selected = false
});
SelectList selectList = new SelectList(selectItems, "Value", "Text");
return selectList;
}

Dropdowns not rendered when override object.cshtml MVC4

My actual problem was mentioned here.
Hide property of model in dynamic view
To solve the problem, I have overrided object.cshtml as mentioned in the answer.
However, when I did this, the dropdowns that I am rendering using UIHints are not working.
In place of dropdown, just False, False False (the no.of Falses are equal to number of list items I have in my viewdata) are displayed.
I am not sure what is happening here, can somebody advise what is going on?
in my controller:
ViewData["PartyRoleTypeId"] = (IEnumerable<SelectListItem>)PartyRoleTypeRepo.All()
.ToList()
.Select(p => new SelectListItem { Value = p.PartyRoleTypeId.ToString(), Text = p.Caption, Selected = p.PartyRoleTypeId == obj.PartyRoleTypeId });
ViewData["PartyId"] = (IEnumerable<SelectListItem>)PartyRepo.All()
.ToList()
.Select(p => new SelectListItem { Value = p.PartyId.ToString(), Text = p.Organization.Caption, Selected = p.PartyId == obj.PartyId });
My dropdown edit template in shared/editortemplates/DropDownList.cshtml
#{
var fieldName = ViewData.ModelMetadata.PropertyName;
}
#Html.DropDownList("",(IEnumerable<SelectListItem>)ViewData[fieldName], "Choose..." , new { #class ="combo"})
object.cshtml
#functions
{
bool ShouldShow (ModelMetadata metadata)
{
return metadata.ShowForEdit
&& metadata.ModelType != typeof(System.Data.EntityState)
&& !metadata.IsComplexType
&& !ViewData.TemplateInfo.Visited(metadata);
}
}
#if (ViewData.TemplateInfo.TemplateDepth > 1)
{
if (Model == null)
{
#ViewData.ModelMetadata.NullDisplayText
}
else
{
#ViewData.ModelMetadata.SimpleDisplayText
}
}
else
{
//ViewData.Clear();
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => ShouldShow(pm)))
{
if (prop.HideSurroundingHtml)
{
#Html.Editor(prop.PropertyName)
}
else if (prop.DisplayName == "Id")
{
<div></div>
}
else if (!string.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString()))
{
<div class="editor-label">#Html.Label(prop.PropertyName)</div>
}
<div class="editor-field">#Html.Editor(prop.PropertyName) #Html.ValidationMessage(prop.PropertyName, "")</div>
}
}
There is some problem with keeping my dropdown values in ViewData or ViewBag.
When I use these, for prartyroletypeid it is not recognizing UIHint dropdownlist.cshtml. It is still referring to object.cshtml.
Instead I kept the dropdown data in TempData and everything is working fine.
But not sure, if I can use TempData in this context.
Any ideas???

Unable to add images to Telerik Tree View

Here I'm going to add Telerik Tree View using MVC 4.Tree is populating.But when i tries to add Image, then it failed..
My code goes here
#(Html.Telerik().TreeView()
.Name("TreeView")
.BindTo(Model, mappings =>
{
mappings.For<myMVCapp.Models.ProjectTree>(binding => binding
.ItemDataBound((item, node) =>
{
if (item.Text == "News Project")
{
item.ImageUrl = "~/Content/Images/myimg.png";
}
item.Text = node.RootNodeText;
})
.Children(node => node.ChildNodes)
);
mappings.For<MyEntityModel.Project>(binding => binding
.ItemDataBound((item, subNodes) =>
{
item.Text = subNodes.ProjectName;
}));
})
)
Any one have idea about how to add image ?
You try to compare item.Text with something before giving it a value. So inside your if expression the item.Text will be always null so your item.ImageUrl = ... line won't be executed.
So do the value assignment before the if:
item.Text = node.RootNodeText;
if (item.Text == "News Project")
{
item.ImageUrl = "~/Content/Images/myimg.png";
}
Or use the node.RootNodeText in your if:
if (node.RootNodeText == "News Project")
{
item.ImageUrl = "~/Content/Images/myimg.png";
}
item.Text = node.RootNodeText;

Html.CheckBox not being set [asp.net mvc 4]

I am having a bit of a headache with a thing (I know something like has been asked before, but I'm pretty sure it's not quite the same thing).
To the point:
I have a View with a Telerik grid. On that grid I show some stuff from the model that I pass to the View BUT I want in the final column to put a CheckBox that is checked/unchecked based on some things in the Controller (the checks have nothing to do with the model that is being passed). In my ActionResult function that takes care of the View I store some Boolean values in the ViewData, and then I set the isChecked value in the CheckBox based on the values stored in the ViewData.
The code for the ActionResult is as follows:
[SecureThis(Roles = "User")]
public ActionResult Index()
{
//get bucket ids
var buckets = db.Buckets.ToList();
int i=1;
string cb = "checkbox" + i.ToString();
foreach (Bucket b in buckets)
{
var payByInvoice = db.PaymentOptions.Where(p => p.BucketId == b.Id).Select(p => p.CanPayByInvoice).SingleOrDefault();
if (payByInvoice == (int)PayByInvoiceState.Accepted)
ViewData["checkbox" + i.ToString()] = true;
else ViewData["checkbox" + i.ToString()] = false;
i++;
cb = "checkbox" + i.ToString();
}
return View(db.Buckets);
}
And the grid that should show all the stuff is this:
#{
int i=1;
string cb = "checkbox" + i.ToString();
}
#(Html.Telerik().Grid(Model)
.Name("BucketsGrid")
.DataKeys(keys => keys.Add(bucket => bucket.Id))
.Columns(
columns =>
{
columns.Template(model => ViewData[model.Id.ToString()])
.HeaderTemplate(
#<b>#Strings.Title_Customer</b>
);
columns.Bound(model => model.CreditFacility);
columns.Bound(model => model.Minimum);
columns.Bound(model => model.RefillLevel);
columns.Bound(model => model.NotificationEmail);
columns.Bound(model => model.NotificationSms);
columns.Template(model => Html.ActionLink(Strings.Edit, "Edit", new { id = model.Id }));
columns.Template(model => Html.ActionLink(Strings.NotificationOptions, "Bucket", "NotificationOptions", new { id = model.Id }, null));
columns.Template(model => Html.ActionLink("Refill", "Refill", "Payment", new { id = model.Id }, null));
columns.Template(model => Html.ActionLink(Strings.Details, "Details", new { id = model.Id }));
columns.Template(model => Html.ActionLink(Strings.Delete, "Delete", new { id = model.Id }));
columns.Template(model => Html.CheckBox("invoice", (Boolean)ViewData[#cb])).HeaderTemplate("Invoice Option");
#i++;
#cb = "checkbox" + i.ToString();
}
)
.Pageable(paging =>
paging.Enabled(true)
.PageSize(UserSettings.GridPageSize)
.Style(GridPagerStyles.NextPrevious)
.Position(GridPagerPosition.Bottom)
)
.Sortable()
.Scrollable()
.Resizable(resize=> resize.Columns(true))
)
The problem with this whole thing is that the checkboxes remain unchecked, no matter the data stored in the ViewData. I went with the debugger and the values are se accordingly in the ViewData, but for some reason (that I cannot yet tell) the checkboxes still remain unchcked.
Any ideas on this matter would be much appreciated.
I have found out the problem of all this. As expected, it was my own doing (or so to say). The problem was that I incremented the #i variable inside the Telerik grid declaration, thinking that it would happen for all the rows in the grid, but that thing is only triggered once. Hence, the ViewData[#cb] value would always have the 2nd value set in the Controller (which in my case was false) and all the checkboxes would then be unchecked.
The fix:
I used the ViewBag and set it up with a Dictionary<Guid, bool> to hold my values, and iterate through it using the model.Id property. For anyone who might be interested I'll post the code below.
Controller:
ViewBag.Dict = new Dictionary<Guid, bool>();
Dictionary<Guid, bool> dict = new Dictionary<Guid, bool>();
foreach (Bucket b in buckets)
{
var payByInvoice = db.PaymentOptions.Where(p => p.BucketId == b.Id).Select(p => p.CanPayByInvoice).SingleOrDefault();
if (payByInvoice != (int)PayByInvoiceState.Accepted)
{
dict.Add(b.Id, false);
}
if (payByInvoice == (int)PayByInvoiceState.Accepted)
{
dict.Add(b.Id, true);
}
}
ViewBag.Dict = dict;
View:
columns.Template(model => Html.CheckBox("invoice", (bool)ViewBag.Dict[model.Id])).HeaderTemplate("Invoice option");