Sitecore Accessing Field value to ASP Control - field

Can any one tell me if I can use a ASP Control instead of Field Renderer to display the field.Please see below illustration.
Note:I need to do it in the Item Databound Event of Repeater.
I have a template with Field as External Link .Eg :Contact US .One way to display that link in the page is using field renderer as below.
ContactUS.aspx:
<asp:Repeater ID="rptContactUS" runat="server" OnItemDataBound="Menu_OnItemDataBound">
<ItemTemplate>
<item><sc:FieldRenderer ID="frContactUS" runat="server"/></item>
</ItemTemplate>
</asp:Repeater>
ContactUS.aspx.cs:
protected void Menu_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
Field item = (Field)e.Item.DataItem;
if (item != null)
{
FieldRenderer frContactUS= (FieldRenderer)e.Item.FindControl("frContactUS");
if (frContactUS!= null)
{
frContactUS.FieldName = item.Name;
}
}
}
The above code works fine.My Question is Whether I can use a Asp control instead of FieldRenderer and assign the link value from the Field Item to asp href property of the link in item databound event of repeater.If yes,Please tell me how?
Thanks,
Suhas

Yes you can. From what I see in your example you are binding Field to the Menu.
You could also bind a List of Items to your menu. You can then retrieve the item's fields in the repeater like this:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Item dataItem = (Item)e.Item.DataItem;
System.Web.UI.WebControls.HyperLink hl = (System.Web.UI.WebControls.HyperLink)e.Item.FindControl("hl");
if (hl != null)
{
Sitecore.Data.Fields.LinkField url = dataItem.Fields["linkfield"];
if (url != null)
{
hlMerk.NavigateUrl = url.Url;
hlMerk.Target = url.Target;
// more properties are available check sitecore documentation
}
}
}
}
From here you will have the url field (obviously you should give the correct field name instead of url.
The LinkField has several properties as described in the general Sitecore documentation that can be found # http://sdn.sitecore.net.

Related

How to assign default value for dropdown list in Umbraco?

I have created custom data type based on built-in dropdown list, but cannot figure out how to specify default value for the list. The default value is always blank:
The default dropdown does not support default value
There is two way of achieving what you want
create your own dropdown datatype (or use a plugin someone else has made - I am not sure which one support it, but maybe have a look at nuPickers )
since it is your custom made you can control it. More about how to create one checkout doc Tutorial - Creating a property editor
use a web api handler to intercept the call of getting the content value - and set a default value to your property if it is empty (null)
below is some un-tested code:
first create the web api handler
public class SetDropdownDefaultHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync
(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
var url = request?.RequestUri?.AbsolutePath.ToLower;
// only process when a create (getempty) or editing a specific content (getbyid)
if (url == "/umbraco/backoffice/umbracoapi/content/getempty"
|| url == "/umbraco/backoffice/umbracoapi/content/getbyid")
{
var content = (ObjectContent)response.Content;
var data = content?.Value as PagedResult<ContentItemBasic<ContentPropertyBasic, IContent>>;
if (data?.Items != null)
{
var tempResult = data?.Items?.ToList();
foreach (var item in tempResult)
{
foreach (var prop in item?.Properties?.Where(p => p?.Editor == "Umbraco.DropDown"))
{
var propStr = prop.Value?.ToString();
if (!propStr.IsNullOrWhiteSpace())
{
// set your default value if it is empty
prop.Value = "your default option prevalue id";
}
}
}
data.Items = tempResult;
}
}
return response;
}
}
then register it at started event
public class UmbracoEvent : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
GlobalConfiguration.Configuration.MessageHandlers.Add(new SetDropdownDefaultHandler());
}
}
your problem maybe you don't know your prevalueid - you can look it up in db or you could use datatype service to get the datatype prevalues then decide which to put as default
Look at: FieldType.DropDownList in the fieldTypes folder.
Replace:<option value=""></option>
With:
var settings = Model.AdditionalSettings;
<option value="">#settings["DefaultValue"]</option>
Then ensure you set the default value property in your dropdown list in the Umbraco Forms backoffice for the given form

How to retain data (form) on custom pagination using MVC?

I have a grid (list generated using scaffolding option) with search criteria. And I created paging concept. I entered search criteria data and search, after post back, I retained the form data using TempData. But, if I click page numbers in grid, the form data not retained and also the grid also getting refreshed.
Is there any way to retain data on pagination?
Thanks!
I added a hidden field dynamically within the form using JavaScript. The page number stored in hidden field, when the user click page number, then submit the form. It is working well without any issue.
Paging:
<button onclick="navigateTo(this, '#Url.RouteUrl("Defined_Route", new { currentPage = j })');">#j</button>
Javascript:
$(function () { //Page Load - Create hidden field, if search button found
if ($("#search")) // Button id
{
var element = document.createElement("input");
element.type = "hidden";
element.id = "currentPage";
element.name = "currentPage";
element.value = '#TempData["Page"]';
if (isNaN(element.value)) element.value = "1";
$(to).parent().append(element);
}
});
function navigateTo(field, url)
{
$("#currentPage").val(field.innerText);
if (isNaN($("#currentPage").val()))
{
location.href = url;//This is for direct url, ie. no search form
}
else
{
$("form").action = url;
$("form").submit();
}
}

ZK set selected item after AnnotateDataBinder loadAll()

I'm new to ZK. I have a Listbox with a List as model. When I receive an update event I update the information in the model and then I update the UI using
AnnotateDataBinder binder = (AnnotateDataBinder) vesselsList.getPage().getAttribute("binder");
if (binder != null) {
binder.loadAll();
}
The problem is that after the update, in the following code
List updatedObjects = object.getItems();
for (Object obj : updatedObjects) {
Listitem data = (Listitem) obj;
Object ob = data.getValue();
The data.getValue() is always null.
I have search the internet for many days and I found that the binder launches an onInitRenderLater event after load everything but I can't manage to make it work.
My intent is if I have an item selected before the update,I want it to remain selected and the binder.loadAll().
Did you setValue to your items with annotated databinding ?
<listitem value="#{bean.data}" > .... </listitem>
In zul I made
<listbox model="#{objects_model}" id="objectsList"
and in Java I call the method
public void onAfterRender$objectsList(Event event) {
// select item here after the listbox has been rendered
}
it did the trick

ASP MVC 2: Jquery modal popup, how to return data

I'm looking into adding a jquery modal popup to my mvc project. I have been looking at http://www.weirdlover.com/2010/05/20/mvc-render-partial-modal-pop-up-via-jquery-and-colorbox-demo/ posting.
My scenario:
I have a page with a few input fields (textbox, checkbox). I want to have a link that will open a modal popup to select an image. I have a control that will display all images and allow the user to select an image. I understand how to open the modal popup following the site listed above.
What I'm not understanding right now is how to return the selected image name (myimage.jpg) to my original pages view and set it to a property on the model with all the other model changes kept intact.
What I have currently:
MyFormController > ActionMethod:ImageSelected(ImageSelectorModel model)
If it is valid, how do I grab my "MyFormModel" (with all other changes), set MyFormModel.ImageName = model.ImageName and call View(myFormModel).
Thanks for your help
Kevin
I would do it with a hidden input field on the main form. when the user clicks an image in the modal popup, use jQuery to handle the click event and assign the value of the image clicked (the filename?) to the hidden input field. if you name the hidden input field correctly, the ModelBinder will automatically bind the filename to your model object, and you won't need to update it manually.
on main form:
<%= Html.HiddenFor( x => x.ImageFileName ) %>
some jQuery:
$("#popup a.candidateImage").click(function() {
$("form input[name=ImageFileName]").value = $("img", this).attr("src");
// probably also close the modal?
}
I didn't test this, but you should get the idea... I would probably also try to show a thumbnail of the file in ImageFileName on the main form if it's been populated.
If the user is uploading an image, I recommend that you check out AJAX Upload: http://valums.com/ajax-upload/. You can grab the image file asynchronously, save it to disk, and return the saved image path (etc.) as a JsonResult. The javascript would look something like this:
new AjaxUpload('image-input', {
action: '/Photo/Add',
onComplete: function (file, response) {
//using Fowler's json2
var photo = JSON.parse(response);
if (photo.IsValid) {
//do what you want with your photo
//photo.Path should contain the saved image's location
}
else {
alert("Sorry. You tried to upload an invalid file.");
}
}
});
And in your Photo controller:
[HttpPost]
public JsonResult Add(HttpPostedFileBase UserFile)
{
if (UserFile == null)
{
//something bad happened, no file
}
string filePath = "/Path/To/Image/Image.jpg";
//this isn't unit test friendly.
//just quick and dirty:
string fullPath = HostingEnvironment.MapPath(filePath);
UserFile.SaveAs(fullPath);
var model = new JsonPhotoAdd
{
IsValid = true,
Path = filePath
};
return Json(model, "text/html");
}
Keep in mind: this is a workaround, as browsers guard against asynchronous file uploads. As such, you might want to consider adding a second page to your form submission process. On that second page, users can handle uploading images with a standard file input field and a form post. http://forums.asp.net/p/1237419/2253919.aspx
I use ASP.NET MVC2 and the NEW VERSION of AjaxUploader:
When I call my Controller:
public JsonResult AddImg(HttpPostedFileBase UserFile)
UserFile is always null...
the script:
function createUploader() {
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader-demo1'),
action: '/Evenement/AddImg',
name: 'UserFile',
});
}
In my view, the form is OK
<% using (Html.BeginForm("AddImg", "Evenement", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<div id="file-uploader-demo1"></div>
<% } %>
Do you have an Idea ? Many thanks and sorry for my bad english^^ i'm french.

Model state inferno - how can Model.A be two different things at the same time?

I have this
<%=Model.StartDate%>
<%=Html.Hidden("StartDate", Model.StartDate)%>
it outputs:
2010-05-11 11:00:00 +01:00
<input type="hidden" value="2010-03-17 11:00:00 +01:00" name="StartDate" id="StartDate">
What the...
It's a paging mechanism so the hidden value was valid on the first page and I've been able to move forward to the next page. But since the values won't update properly it ends there.
What do I need to do?
Using firefox.
Update - more code
using (Html.BeginForm("Program", "Activities", null, FormMethod.Get, new { #name = "ProgramForm", id = "ProgramForm" }))
{
.
viewModel.StartDate = pagingService.StartDate;
return View(viewModel);
Update - complete action
[Authorize]
public ActionResult Program(string[] submit)
{
var viewModel = new ActivityProgramViewModel { UserID = LoggedInUser.UserID };
viewModel.Fresh = true;
TryUpdateModel(viewModel);
var pagingService = new OccurencePagingService(LoggedInUser.AllActivities.Where(a => a.StartTime != null));
if (!viewModel.Fresh)
{
pagingService.StartDate = ((DateTimeOffset)viewModel.StartDate);
pagingService.EndDate = ((DateTimeOffset)viewModel.EndDate);
}
if (submit != null)
if (submit.Contains("MoveBack"))
pagingService.MoveBack();
else if (submit.Contains("MoveForward"))
pagingService.MoveForward();
ViewData.Model = viewModel;
viewModel.Occurrences = pagingService.GetOccurences();
viewModel.Fresh = false;
viewModel.HasLess = pagingService.HasLess;
viewModel.HasMore = pagingService.HasMore;
viewModel.StartDate = pagingService.StartDate;
viewModel.EndDate = pagingService.EndDate;
return View();
}
First one uses Model object, second one uses existing ModelState. Look at ModelState values before generating view. It propably holds value for this field. Html helpers priveded by MVC use ModelState to generate form fields. It helps in recreating values after post back.
To get rid of this kind of problems, use POST-REDIRECT-GET pattern or just pass query parameters through GET.
I think the <%=Html.Hidden("StartDate", Model.StartDate)%> is out of place here.
Html Helpers try to keep data in the UI like they where entered by examining the post/route data. Please dont ask me how someone would ever enter data in a hidden field.
You want something different: You want to set the data to Model.StartDate and dont care what is in the post/route.
I would use <input value="<%=Model.StartDate%>" name="StartDate" /> .

Resources