New to MVC and Stackoverflow so sorry for not having enough reputation to post images...
Trying to render a ListBox with pre selected values
My SQL Database:
http://i.imgur.com/bcdXyqE.png
My Entity Framework
http://i.imgur.com/wYWXuAq.png
My Controller
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
var roles = db.Role;
var newList = new List<SelectListItem>();
foreach (var role in roles)
{
newList.Add(
new SelectListItem()
{
Value = role.Id.ToString(),
Text = role.RoleName,
Selected = user.Role.Contains(role)
}
);
}
ViewBag.x = new SelectList(newList, "Value", "Text");
ViewBag.Roles = new SelectList(db.Role, "Id", "RoleName", user.Role);
return View(user);
}
My View
<p>try1:</p>
#Html.ListBox("Roles", null, new { #class = "form-control", #size = 6, #style = "height: initial" })
<p>try2:</p>
#Html.ListBox("x", null, new { #size = 6, #style = "height: initial" })
Non of the 2 tries renders with pre selected values?
got it working.
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
IEnumerable<SelectListItem> roles = db.Role.Select(c => new SelectListItem{ Value = c.Id.ToString(), Text = c.RoleName, Selected = true});
var rolesSelected = new int[user.Role.Count];
var i = 0;
foreach (var role in user.Role)
{
rolesSelected[i] = role.Id;
i++;
}
ViewBag.Roles = roles.ToList();
ViewBag.RolesSelected = rolesSelected;
return View(user);
}
#Html.ListBox("RolesSelect", new MultiSelectList(ViewBag.Roles, "Value", "Text", ViewBag.RolesSelected), new { #class = "form-control", #size = 6, #style = "height: initial" })
Related
I want to populate a dropdown with values A,Band C.The below code works for create only,not for edit.
ViewBag.UserType = new[] { new SelectListItem { Text = "A", Value = "1", Selected = false }, new SelectListItem { Text = "B", Value = "2", Selected = false }, new SelectListItem { Text = "C", Value = "3", Selected = false } };
So I created an anonymous class. I have an anonymous class like below.
var Roles= new[]
{ new { Id =1,UserType="A" },
new {Id=2,UserType="B" },
new {Id=3,UserType="B" }
};
ViewBag.Type = Roles.ToList();
But i dont know how to fill dropdown in View.
#Html.DropDownListFor(model => model.UserType, ((IEnumerable<SelectListItem>)ViewBag.UserType).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Text),
Value = option.Value.ToString(),
Selected = (Model != null) && (option.Value == (Model.UserType).ToString())
}),"Select")
What changes should i make in the view
Add following properties to your ViewModel class -
public SelectList Roles
{
get
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem
{
Value = "1",
Text = "A",
});
items.Add(new SelectListItem
{
Value = "2",
Text = "B",
});
items.Add(new SelectListItem
{
Value = "3",
Text = "C",
});
return new SelectList(items, "Value", "Text");
}
}
public int SelectedRole { get; set; }
and bind in View as follows -
#Html.DropDownListFor(model => model.SelectedRole, Model.Roles)
I am using MVC 3, in my project i have 2 view, i want to open 2nd view in 1st View popup
My 1st View is by that i want to Open 2nd View in PopUp,
#model CustomerAddressListModel
#using Nop.Web.Models.Customer;
#{
Layout = "~/Views/Shared/_ColumnsTwo.cshtml";
//title
Html.AddTitleParts(T("PageTitle.Account").Text);
}
<script type="text/javascript">
$(function () {
$('a.dialog').click(function () {
var url = $(this).attr('href');
var dialog = $('<div style="display:none"></div>').appendTo('body');
dialog.load(url, {}, function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
close: function (event, ui) {
dialog.remove();
}
});
});
return false;
});
});
</script>
<div class="add-btn-cntrnr left" style="width:400px;">
#Html.ActionLink("AddLink", "AddressAdd", "Customer", new { #class = "dialog" })
</div>
and this is my second view which i want to open in PopUp:
#model CustomerAddressEditModel
#using Nop.Web.Models.Customer;
#{
Layout = null;
}
#using Nop.Web.Framework;
#using (Html.BeginForm())
{
<div class="emai_head">
<span class="emai_head_text">Add Address</span>
#{
var dataDictAddress = new ViewDataDictionary();
//Merge ModelState (required for validation)
dataDictAddress.ModelState.Merge(ViewData.ModelState);
dataDictAddress.TemplateInfo.HtmlFieldPrefix = "Address";
#Html.Partial("_CreateOrUpdateAddress", Model.Address, dataDictAddress)
}
<input type="submit" class="acc_btnn" value=" " />
</div>
}
This is my controller for PopUp view :
[NopHttpsRequirement(SslRequirement.Yes)]
public ActionResult AddressAdd()
{
if (!IsCurrentUserRegistered())
return new HttpUnauthorizedResult();
var customer = _workContext.CurrentCustomer;
var model = new CustomerAddressEditModel();
model.NavigationModel = GetCustomerNavigationModel(customer);
model.NavigationModel.SelectedTab = CustomerNavigationEnum.Addresses;
model.Address = new AddressModel();
//countries
model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries())
model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString() });
model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });
return View(model);
}
[HttpPost]
public ActionResult AddressAdd(CustomerAddressEditModel model)
{
if (!IsCurrentUserRegistered())
return new HttpUnauthorizedResult();
var customer = _workContext.CurrentCustomer;
model.NavigationModel = GetCustomerNavigationModel(customer);
model.NavigationModel.SelectedTab = CustomerNavigationEnum.Addresses;
if (ModelState.IsValid)
{
var address = model.Address.ToEntity();
address.CreatedOnUtc = DateTime.UtcNow;
//some validation
if (address.CountryId == 0)
address.CountryId = null;
if (address.StateProvinceId == 0)
address.StateProvinceId = null;
customer.Addresses.Add(address);
_customerService.UpdateCustomer(customer);
// return RedirectToRoute("CustomerAddresses");
}
//If we got this far, something failed, redisplay form
//countries
model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries())
model.Address.AvailableCountries.Add(new SelectListItem() { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString(), Selected = (c.Id == model.Address.CountryId) });
//states
var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value).ToList() : new List<StateProvince>();
if (states.Count > 0)
{
foreach (var s in states)
model.Address.AvailableStates.Add(new SelectListItem() { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.Address.StateProvinceId) });
}
else
model.Address.AvailableStates.Add(new SelectListItem() { Text = _localizationService.GetResource("Address.OtherNonUS"), Value = "0" });
return View(model);
}
My partialview didnot load, i'm using AjaxActionLink
here is my view where i call my partialview
#foreach (var p in Model.Rooms)
{
<div class="room">
<h3>#p.RoomTitle</h3>
<img src="#p.PhotoRoom" alt="room"/>
<h4>#p.TitlePrice</h4>
<blockquote>#p.Description</blockquote>
#Ajax.ActionLink("Order room", "PartialDetail", new { #p.RoomID }, new AjaxOptions { UpdateTargetId = "results", LoadingElementId = "loading",HttpMethod = "POST",InsertionMode = InsertionMode.InsertAfter})
</div>
}
Here is my controller
public PartialViewResult PartialDetail(int roomid)
{
Room rooms =
repository.Room.FirstOrDefault(p => p.RoomID == roomid);
var viewModel = new RoomEditViewModel
{
RoomID = rooms.RoomID,
RoomTitle = rooms.RoomTitle,
Description = rooms.Description,
PhotoRoom = rooms.PhotoRoom
};
ViewBag.room = roomid;
return PartialView(viewModel);
}
fixed your ajax action link
What you set
#Ajax.ActionLink("Order room", "PartialDetail", new { #p.RoomID }
Should be
#Ajax.ActionLink("Order room", "PartialDetail", new { roomid = #p.RoomID }
As a recommendation set the aceepted protocols in your action
[HttpPost]
public PartialViewResult PartialDetail(int roomid)
I am trying to bind a Telerik DropDownList.
View Code:
<div>#( Html.Telerik().DropDownList()
.Name("ddlCounty")
.HtmlAttributes(new { style = "width:200px;" })
.SelectedIndex(0)
.BindTo(new SelectList((IEnumerable<MvcNew.Models.tbl_Country>)ViewData["ListCountries"], "Value", "Text")) )
</div>
Controller Code:
List<SelectListItem> lst_Country = new List<SelectListItem>();
var Countries = (from m in DBContext.tbl_Countries
select new SelectListItem{ Text = m.Country__Name.ToString(), Value = m.Country_ID.ToString() });
ViewBag.ListCountries = new SelectList(Countries);
return View();
I am getting the below error
Unable to cast object of type 'System.Web.Mvc.SelectList' to type 'System.Collections.Generic.IEnumerable`1[MvcNew.Models.tbl_Country]'.
I have changed a code like this and it's worked
var clientIDs = DBContext.tbl_Countries
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in clientIDs)
{
SelectListItem s = new SelectListItem();
s.Text = t.Country__Name.ToString();
s.Value = t.Country__Name.ToString();
items.Add(s);
}
ViewBag.ListCountries = items;
I am using .NET Web API and of course returning classes that are serialized to JSON. Up Until now I have not had to use the Data Contract attribute for any classes, but for this class below I do and I have no idea why. Intellitrace just says the class is unable to be serialized and to try adding a DataContract Attribute. I will but want to know why.
public class Card : BaseGridVM
{
private IEnumerable<Pc> _pcCards;
private IEnumerable<Pt> _ptCards;
private IEnumerable<MembershipCard> _membershipCards;
public Grid.Result Pt
{
get { return GetPtCardGrid(); }
}
public Grid.Result Pc
{
get { return GetPcCardGrid(); }
}
public Grid.Result Membership
{
get { return GetMembershipCardGrid(); }
}
public Card(IEnumerable<Pc> pcCards, IEnumerable<Pt> ptCards, IEnumerable<MembershipCard> membershipCards)
{
_pcCards = pcCards;
_ptCards = ptCards;
_membershipCards = membershipCards;
}
private Grid.Result GetPtCardGrid()
{
var headers = new List<Grid.Header>
{
new Grid.Header() {label = "Card Name", width = 250},
new Grid.Header() {label = "Pts", width = 50},
new Grid.Header() {label = "Activation Date", width = 50}
};
var rows = new List<Grid.Row>();
foreach (var card in _ptCards)
{
var row = new Grid.Row
{
id = card.id,
enabled = card.active.HasValue && (bool)card.active,
cell = new string[3]
};
row.cell[0] = card.cardName;
row.cell[1] = card.pts.HasValue ? card.pts.ToString() : "0";
row.cell[2] = card.activationDate.HasValue ? card.activationDate.ToString() : "-";
rows.Add(row);
}
return buildGrid(rows, headers, 1, 3);
}
private Grid.Result GetPcCardGrid()
{
var headers = new List<Grid.Header>
{
new Grid.Header() {label = "Offer Title", width = 200},
new Grid.Header() {label = "Pces Required", width = 70},
new Grid.Header() {label = "Activation Date", width = 50}
};
var rows = new List<Grid.Row>();
foreach (var card in _pcCards)
{
var row = new Grid.Row
{
id = card.id,
enabled = card.active.HasValue && (bool)card.active,
cell = new string[3]
};
row.cell[0] = card.cardName;
row.cell[1] = card.pces.HasValue ? card.pces.ToString() : "0";
row.cell[2] = card.creationDate.HasValue ? card.creationDate.ToString() : "-";
rows.Add(row);
}
return buildGrid(rows, headers, 1, 3);
}
private Grid.Result GetMembershipCardGrid()
{
var headers = new List<Grid.Header>
{
new Grid.Header() {label = "Card Name", width = 200},
new Grid.Header() {label = "Members", width = 70}
};
var rows = new List<Grid.Row>();
foreach (var card in _membershipCards)
{
var row = new Grid.Row
{
id = card.id,
enabled = card.active.HasValue && (bool)card.active,
cell = new string[2]
};
row.cell[0] = card.cardName;
row.cell[1] = card.membersCount.HasValue ? card.membersCount.ToString() : "0";
rows.Add(row);
}
return buildGrid(rows, headers, 1, 3);
}
}
This is Base GridVM
public abstract class BaseGridVM
{
protected static Grid.Result buildGrid(IEnumerable<Grid.Row> rows, IEnumerable<Grid.Header> headers, int page, int steps)
{
var row_array = rows.ToArray();
var result = new Grid.Result
{
rows = row_array,
page = page,
records = row_array.Count(),
steps = steps,
headers = headers.ToArray()
};
return result;
}
}
And this is another Class where a Data Contract is not requested
public class DashboardVM : IDashboardVM
{
public IResults_Dashboard results { get; private set; }
public Grid.Result topCompaniesGrid
{
get { return BuildTopCompanies(); }
}
public Grid.Result topAdsGrid
{
get { return BuildTopAds(); }
}
public DashboardVM(IResults_Dashboard results)
{
this.results = results;
}
private static Grid.Result buildGrid(IEnumerable<Grid.Row> rows, IEnumerable<Grid.Header> headers, int page, int steps)
{
var row_array = rows.ToArray();
var result = new Grid.Result
{
rows = row_array,
page = page,
records = row_array.Count(),
steps = steps,
headers = headers.ToArray()
};
return result;
}
private Grid.Result BuildTopCompanies()
{
var headers = new List<Grid.Header>
{
new Grid.Header() {label = "Company Name", width = 150, click = true},
new Grid.Header() {label = "Coupon Views", width = 50, click = true},
new Grid.Header() {label = "Coupon Clicks", width = 50},
new Grid.Header() {label = "Coupon Redemptions", width = 50},
new Grid.Header() {label = "Ad Views", width = 50, click = true},
new Grid.Header() {label = "Ad Clicks", width = 50},
new Grid.Header() {label = "Reward Cards", width = 50},
new Grid.Header() {label = "Fees", width = 50}
};
var rows = new List<Grid.Row>();
foreach (var company in results.companies)
{
var row = new Grid.Row {id = Convert.ToInt32(company.companyId), cell = new string[8]};
row.cell[0] = company.companyName;
row.cell[1] = company.couponViews.ToString();
row.cell[2] = company.couponClicks.ToString();
row.cell[3] = company.couponRedemptions.ToString();
row.cell[4] = company.adViews.ToString();
row.cell[5] = company.adClicks.ToString();
row.cell[6] = company.rewardCards.ToString();
row.cell[7] = company.revenue.ToString();
rows.Add(row);
}
return buildGrid(rows, headers, 1, 3);
}
private Grid.Result BuildTopAds()
{
var headers = new List<Grid.Header>
{
new Grid.Header() {label = "Company Name", width = 150, click = true},
new Grid.Header() {label = "Ad Name", width = 150, click = true},
new Grid.Header() {label = "Views", width = 50},
new Grid.Header() {label = "Clicks", width = 50},
new Grid.Header() {label = "Fees", width = 50}
};
var rows = new List<Grid.Row>();
foreach (var ad in results.ads)
{
var row = new Grid.Row {id = Convert.ToInt32(ad.Id), cell = new string[5]};
row.cell[0] = ad.companyName;
row.cell[1] = ad.name;
row.cell[2] = ad.views.ToString();
row.cell[3] = ad.clicks.ToString();
row.cell[4] = ad.fees.ToString();
rows.Add(row);
}
return buildGrid(rows, headers, 1, 3);
}
}
I solved this problem without the Data Contract by adding a parameterless constructor and adding set methods to the properties.
What I gathered from this is that the serializer creates a new object using the parameterless constructor and then copies the public values over. I say this because when I did not add the set methods to the properties it gave me an empty object. Once I added the set methods the values were returned within the object.
I think it could be a little more sophisticated. I don't know why it creates another object vs using the one I gave, but that's another topic!