In Umbraco CMS I have created a 6 events. In that 3 were created in January and the other 3 were created in February.
I want to fetch the events created in current month. For that I have used query builder in Umbraco and the query was:
#{
var selection = Umbraco.Content(Guid.Parse("9359beaa-b580-4f2c-8c8f-239f29e560b4"))
.ChildrenOfType("aseanEventsItem")
.Where(x => (x.CreateDate >= DateTime.Now.Date))
.Where(x => x.IsVisible());
}
<ul>
#foreach (var item in selection)
{
<li>
#item.Name
</li>
}
</ul>
It's working fine now. How I can get the current month?
You can use the Model.Content.Children to do that. Here is an example and the screenshot for you:
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#using Umbraco.Core.Models
#using Umbraco.Web
#{
Layout = null;
var lastMonth = DateTime.Now.AddMonths(-1);
var testRoot = Model.Content.Children
.Where(x => x.CreateDate >= lastMonth);
//var selection = Umbraco.Content(Guid.Parse("9359beaa-b580-4f2c-8c8f-239f29e560b4"))
// .ChildrenOfType("aseanEventsItem")
// .Where(x => (x.CreateDate >= DateTime.Now.Date))
// .Where(x => x.IsVisible());
}
<p>TEST template</p>
#foreach (var item in testRoot)
{
<p>#item.Name - #item.CreateDate</p>
}
Related
I have a controller named CallAllocation, and a View CallAllocation.
At first when the page loads only two dropdown appears with a submit button. On submission, page gets filled with rest of the details based on the selection from the two dropdowns. To achieve that I have made the following code:
Please focus on ViewBag.IsValid condition
My Controller be like
[HttpGet]
public ActionResult CallAllocation()
{
ViewBag.UserName = User.Identity.Name.ToString();
try
{
var NatureList = (from a in dataContext.CallNatures
select a);
Allocation Allocate = new Allocation();
Allocate.CallNaturelist = NatureList.ToList();
ViewData["SelectedTicket"] = 0;
Allocate.CallTicketList = null;
ViewBag.IsValid = "";
return View(Allocate);
}
catch (Exception ex)
{
TempData["ErrMsg"] = ex.Message;
return RedirectToAction("ShowError");
}
}
My View be like
#using (Html.BeginForm("CallAllocation", "Home", FormMethod.Post, new { id = "FrmCallAllocate"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
#Html.Raw(ViewBag.ErrMsg)
<div class="row ">
<div class="col-sm-12">
#if (ViewBag.IsVaild == "True")
{
#Html.DropDownListFor(m => m.SelectedCallNature, new SelectList(Model.CallNaturelist, "CallNatureID", "Description"),
"Select Nature", new { style = "width:250px", #class = "dropdown1", #readonly = "readonly;" })
#Html.DropDownList("CallTicket", new SelectList(string.Empty, "CallTicketNumber", "CallTicketNumber"), "Select Call Ticket",
new { style = "width:250px", #class = "dropdown1" , #readonly = "readonly;" })
<input type="submit" value="Get Ticket" style="background-color:#C5C5C5"/>
}
else
{
#Html.DropDownListFor(m => m.SelectedCallNature, new SelectList(Model.CallNaturelist, "CallNatureID", "Description"),
"Select Nature", new { style = "width:250px", #class = "dropdown1" })
#Html.DropDownList("CallTicket", new SelectList(string.Empty, "CallTicketNumber", "CallTicketNumber"), "Select Call Ticket",
new { style = "width:250px", #class = "dropdown1"})
<input type="submit" value="Get Ticket" style="background-color:#C5C5C5"/>
}
</div>
</div>
}
As you can see Controller sends ViewBag value "", and it should enter else condition of the View. But it is bypassing both the conditions.
Please help me understand why the controller is unable to send Viewbag value to the view. I have made similar cases but it's working in rest.
I have tried clearing the cache too.
Please note that my View is a strongly-typed View.
I have my code written as follows
var RecentTransactions = db.Leave_Data.OrderByDescending(l => l.Applied_Date).Take(5).Select(x => new
{
StartDate = x.Start_Date,
LeavePurpose = x.Leave_Purpose,
LeaveType = x.Leave_Type.Leave_Type1,
LeaveStatus = x.Leave_Status.Status_Name
});
ViewBag.RecentTransactions = RecentTransactions.ToList();
This is how I written in my view
#foreach (var item in ViewBag.RecentTransactions)
{
<li class="list-group-item">
<span class="pull-right">#item.LeaveStatus</span>
</li>
}
Additional information: 'object' does not contain a definition for 'LeaveStatus'
So can some one help me
Updated code if any better way let me know
List<Leave_Data> ld = new List<Leave_Data>();
Leave_Data l = new Leave_Data();
var RecentTransactions = db.Leave_Data.OrderByDescending(i => i.Applied_Date).Take(5).Select(x => new
{
StartDate = x.Start_Date,
LeavePurpose = x.Leave_Purpose,
LeaveType = x.Leave_Type.Leave_Type1,
LeaveStatus = x.Leave_Status.Status_Name
});
foreach(var result in RecentTransactions)
{
l.Start_Date = result.StartDate;
l.Leave_Purpose = result.LeavePurpose;
l.Leave_Type = new Leave_Type();
l.Leave_Type.Leave_Type1 = result.LeaveType;
l.Leave_Status = new Leave_Status();
l.Leave_Status.Status_Name = result.LeaveStatus;
ld.Add(l);
}
ViewBag.RecentTransactions = ld;
I got the following controls in my view:
<div class="editor-label">
#Html.LabelFor(model => model.Number)
</div>
<div class="editor-field">
#Html.HiddenFor(model => model.Number)
#Html.TextBoxFor(model => model.Number, new { disabled = "disabled" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProjectID)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Project.ID, Model.ProjectList, "Select", new { onchange = "SelectedIndexChanged()" })
</div>
I submit the form when the dropdownlist value change to generate the Number field of the model, then the view is reloaded. When the is no HiddenFor control, the Number of the model is displayed properly in the TextBoxFor. When I add a HiddenFor control, the Number field is not displayed although Model.Number is not null.
What is the reason of this?
The reason why I want a HiddenFor with the Number value is that when I submit the form for saving, model.Number equals null. I thought by putting the value in a HiddenFor I would have access to it...
Edit: Controller method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOpportunity(CreateEditOpportunityModel model)
{
// if the submit is made by the ddl
if (model.SubmitValue.Equals("ChangeProject"))
{
Project parentProject = pCtx.Projects.Find(model.Project.ID);
if (parentProject != null)
{
// Generate the "Number field"
Region projectRegion = rCtx.Regions.Find(parentProject.RegionID);
int numOpportunity = oCtx.Opportunitites.Count(o => o.ProjectID == parentProject.ID);
numOpportunity++;
string oppNumber = numOpportunity < 10 ? "0" + numOpportunity : numOpportunity.ToString();
model.Number = projectRegion.Name + "-" + parentProject.ID + "-" + oppNumber;
}
// Repopulate the ddl
model.ProjectList = new SelectList(pCtx.Projects, "ID", "ID");
return View(model);
}
// if submit is made by the save button
else if (model.SubmitValue.Equals("CreateOpportunity"))
{
if (ModelState.IsValid)
{
Opportunity opportunity = new Opportunity();
opportunity.ID = model.ID;
opportunity.Number = model.Number;
opportunity.ActivationDate = model.ActivationDate;
opportunity.Assignee = model.Assignee;
opportunity.Comments = model.Comments;
opportunity.CreationDate = DateTime.Now;
opportunity.LicenseFilePath = model.LicenseFilePath;
opportunity.LicenseRequestFilePath = model.LicenseRequestFilePath;
opportunity.OkPermanentStatus = model.OkPermanentStatus;
opportunity.PaidStatus = model.PaidStatus;
opportunity.PartNumber = model.PartNumber;
opportunity.Project = pCtx.Projects.Find(model.Project.ID);
//tell EF that Project already exists in Company table
oCtx.Entry(opportunity.Project).State = EntityState.Modified;
// Saves project
oCtx.Opportunitites.Add(opportunity);
oCtx.SaveChanges();
return RedirectToAction("Index");
}
model.ProjectList = new SelectList(pCtx.Projects, "ID", "ID");
return View(model);
}
model.ProjectList = new SelectList(pCtx.Projects, "ID", "ID");
return View(model);
}
This part of the code works fine, I'm just putting it here to clarify things.
I am having a < href > attributes in my .cshtml page at mvc4 #cp.Name
in my mvc 4 .... what i need is if a person clicks the above link . i have to redirect him to any of the ActionName in Controller (for eg: Index in HomeController )...... how to do it. In my above sample i have redirected to google.com...... but i need to redirect to any of actionname in controller......
My code:
<nav> #{ List<MenuRazor.Models.MenuItem> menulist = ViewBag.Menu; }
<ul id="menu">
#foreach (var mp in menulist.Where(p => p.ParentMenu_Id == 0)) {
<li> #mp.Name
#if (menulist.Count(p => p.ParentMenu_Id == mp.Id) > 0)
{ #:<ul> }
#RenderMenuItem(menulist, mp)
#if (menulist.Count(p => p.ParentMenu_Id == mp.Id) > 0){#:</ul> }
</li> }
</ul>
#helper RenderMenuItem(List<MenuRazor.Models.MenuItem> menuList, MenuRazor.Models.MenuItem mi)
{
foreach (var cp in menuList.Where(p => p.ParentMenu_Id == mi.Id)) {
#:<li> #cp.Name
if (menuList.Count(p => p.ParentMenu_Id == cp.Id) > 0) {
#:<ul>
}
#RenderMenuItem(menuList, cp)
if (menuList.Count(p => p.ParentMenu_Id == cp.Id) > 0) {
#:</ul>
} else {
#:</li>
}
} } </nav>
You can use: #Url.Action("ActionName", "ControllerName")
Refer this MSDN link for more information.
You can use #Html.ActionLink or #Url.Action to generated you link.
#Html.ActionLink("Link name", "Action", "Controller", new { id = your_param }, null)
or
#Url.Action("Action", "Controller")
The #Html.ActionLink might better suit your current problem.
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");