I want to access the selectedvalue (enumeration field) in content part when click submit save button in widget administrator. How I can do that in Editor Method?
If you know the name of the ContentPart that has that field, you can do it like this:
(dynamic)contentItem.ContentPartName.FieldName.SelectedValue
But if you don't know the name of the ContentPart, you can first use this to get all the fields of the content item at runtime:
using System.Runtime.CompilerServices;
using Microsoft.CSharp.RuntimeBinder;
// get all the fields from the contentItem without knowing part name
var callSite = CallSite<Func<CallSite, object, object>>
.Create(Binder.GetMember(0, contentItem.ContentType,
((dynamic)contentItem).GetType(), new[] { CSharpArgumentInfo.Create(0, null) }));
var contentItemFields = ((callSite.Target(callSite, ((dynamic)contentItem))).Fields) as List<ContentField>;
Having the list of fields, you now can search for the EnumerationField that you want, and get the selected value:
var yourField = (contentItemFields.FirstOrDefault(f => f.name == "YourField")) as EnumerationField;
var selectedValue = yourField.SelectedValue;
Related
I am creating products from a product template. Each time a customer selects a product to view information about, the data from that product needs to get loaded. I have created a controller, model and view. The model is generated with TDS. I need to pass the item id to the [SitecoreId] from the controller. Here is the code I am using:
From the layout:
#{var id = Sitecore.Data.ID.Parse("{74A67488-8E33-47E2-86F5-25AD23FDF3D3}"); }
#Html.Sitecore().ControllerRendering("ProductOverview", "Index", new { ItemId = #id })
The controller:
public class ProductOverviewController : Controller
{
private readonly IMvcContext _mvcContext;
public ProductOverviewController(IMvcContext mvcContext)
{
_mvcContext = mvcContext;
}
// GET: ProductOverview
public ActionResult Index()
{
var itemId = string.Empty;
var rc = RenderingContext.CurrentOrNull;
if (rc != null)
{
var parms = rc.Rendering.Properties;
itemId = parms["ItemId"];
}
var dataSource = _mvcContext.GetContextItem<ProductOverviewModel> ();
return View(dataSource);
}
}
The itemId var has the correct id that I am passing from the layout (hard coded for now). From here I am at an absolute loss on how to get that into the model. I have tried dozens of suggestions from searches but the model always uses the current item (as set by GlassBase in the model itself) as opposed to the product id that contains the data for that product.
Is what I want to do even possible? Can the [SitecoreId] even be overridden?
The line where you are setting the value for dataSource using Glass Mapper is where you'll want to make your change..
Glass Mapper lets you use a number of different options to get the Item and cast to your "type" which looks to be ProductOverviewModel currently.
you can use the following for example (notice that I've used .SitecoreService.GetItem instead of .GetContextItem ):
//pass the GUID into here (you'd need to cast to a Guid first instead of ID)
var dataSource = _mvcContext.SitecoreService.GetItem<ProductOverviewModel>(guid);
//or if you wanted to get your ID as a Sitecore Item you could use
var dataSource = _mvcContext.SitecoreService.GetItem<ProductOverviewModel>(item.Paths.Path);
I'm fairly new to mvc and razor views.
I have a DropDownListFor that successfully is populated with a list of values and text from a data table.
I also am successfully binding the selected value to a data column in my data model.
However, the database that I'm working with is not normalized and I have need to taking the Text from the selected item, and binding that to another field in my data model.
How hard is it to do this?
You have several options:
1. Call the database to get text after submit
public ActionResult Submit(int dropDownListId)
{
var text = string.Empty;
var dataItem = this._dbContext.SomeTableData.SingleOrDefault(m => m.Id == dropDownListId);
if (dataItem != null)
{
text = dataItem.Title;
}
// continue
}
2. Adjust the drop down list value and parse the value in controller/business layer:
If you're using the default DropDownListFor HtmlHelper your data source is type of IEnumerable<SelectListItem> so while you're building your Model class you're going to pass it to the view, do something like this:
//get data from database
var dataSource = this_dbContext.SomeTableData.Select(m => new SelectListItem()
{
Value = string.Format("{0}|{1}", m.Id, m.Title),
Text = m.Title
}
And after you submit data parse the value:
public ActionResult Submit(string dropDownListValue) {
string[] values = dropDownListValue.Split('|');
// values[0] = value
// values[1] = text
}
3. Add hidden field to the view and use JavaScript to store the text
$('#dropDownListId').on('change', function () {
var text = $(this).find('option:selected').text();
$('#dropDownListText').val(text); // hidden field
});
and collect the value after submit:
public ActionResult Submit(int dropDownListId, string dropDownListText)
{
//logic
}
I am passing a ViewBag list to my view and I am trying to display this list in a listbox so as I can select items of this list.
This is the controller method for the view:
public ActionResult AddMembers(int? id)
{
ViewBag.lstMembers = db.ClubMembers.ToList();
var selClub = db.Clubs.Find(id);
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
return View(selClub);
}
This is what I have currently but it is not displaying the items correctly as shown in the photo below:
#Html.ListBoxFor(m => m.ClubMembers, new SelectList ( ViewBag.lstMembers))
How can I set the source of my listbox so that it will display the items passed in via the ViewBag.lstMembers from the controller method
You need to specify the display member and value member that will be used to render the string representation of the object, otherwise MVC will just call ToString.
SelectList has an overloaded constructor for this e.g.:
new SelectList(items, "ValuePropertyName", "DisplayPropertyName")
see here:
https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist.selectlist(v=vs.118).aspx#M:System.Web.Mvc.SelectList.
you can use MultiSelectList some thing like that
In Action
ViewBag.lstMembers = new MultiSelectList(db.ClubMembers.ToList(), "ValueProperty", "NameProperty");
in View
#Html.ListBox("lstMembers", ViewBag.lstMembers as MultiSelectList)
I have an XML file with several environment names and corresponding URL to the environment name.
Requirement is:
1. display the environment names in a dropdownlist
2. select any environment name in dropdownlist.
3. Click Navigate link below dropdown button.
4. The page should be navigated to particular URL, which the environment name belongs to.
EX: (from XML File)
I want to fetch "name" & "LMHost" .
I completed upto creating dropdownlist. Binding environment name inside dropdownlist. But i dunno how to navigate it to particular URL.
My Controller Code
var xDoc = XDocument.Load(fileName);
IEnumerable<XElement> envGroups = from xmlDoc in xDoc.Descendants().Elements("environment")
select xmlDoc;
model.EnvironmentName = from envName in envGroups.Attributes("name")
select new SelectListItem
{
Text = envName.Value,
Value = envName.Value.ToString(),
Selected = (envName.Equals(envName))
};
return View(model);
View Code
<%=Html.DropDownList("EnvironmentName", new SelectList (Model.EnvironmentName, "Value" , "Text")) %>
Model Code
public IEnumerable _environmentName;
[DisplayName("EnvironmentName")]
public IEnumerable<SelectListItem> EnvironmentName
{
get
{
if (_environmentName == null)
_environmentName = new List<SelectListItem>();
return _environmentName;
}
set { _environmentName = value; }
}
Kindly help me. I find difficult to navigate the environment names to its particular URL
As mentioned above, window.location will work
Include jquery on your page, and add a button or anchor to your page with the onclick action:
window.location=$('#EnvironmentName').val();
You can prefix/suffix the location to create the correct path e.g.:
window.location='http://yoursitepath/' + $('#EnvironmentName').val() + '.html';
In my MVC application I am trying to retrieve data using a stored procedure, then display it in a dropdown.
Here is My controller action
public ActionResult Register(string id )
{
RegistrationModel Student = new RegistrationModel();
using (var db = new StudentEntities())
{
var SportResultList = GetListOfSport();
var SportSelectList = new SelectList(SportResultList);
ViewBag.SportList = SportSelectList;
return View(Student);
}
Here is the Method to get the list using the stored procedure
public static List<GetSportsResult> GetListOfSport()
{
using (var db = new StudentEntities())
{
ObjectResult<GetSportsResult> SportResults = db.GetSportsByStudentIdAndSeason(11111, 1);
List<GetSportsResult> results = SportResults.ToList();
return results;
}
}
The stored procedure returns a complex type called GetSportsResults but I don't now how to access its fields.
Currently this code will display the GetSportsResults 20 times which is the right amount of records I should be getting
In the constructor for SelectList you can specify which fields are to be used for the text and for the value. This is done by passing string values to the constructor.
For example, if your GetSportsResult object has a .ID property as its identifier and a .Name property as its display value, then your code would look like this:
var SportResultList = GetListOfSport();
var SportSelectList = new SelectList(SportResultList, "ID", "Name");
ViewBag.SportList = SportSelectList;
This would indicate to the SelectList object that GetSportsResult.ID should be the value for each item in the list, and GetSportsResult.Name should be the displayed text for each item in the list.
Without specifying these fields, currently the object tries to make a "best guess" of what to display. It's probably doing this by calling .ToString() on each object by default. And the default behavior of .ToString() on a non-primative type is to display the name of the type itself, which is why you're seeing the string "GetSportsResult" for each item.