How to use href attribute in mvc4 - asp.net-mvc-4

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.

Related

How to get current month in Query

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>
}

Controller is not returning Viewbag value to the View

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.

Remember selected checkboxes across paginated pages

I am displaying data in a table and doing some paging and sorting. I have a checkbox for everyrow.
When I move from one page to another, I will like to keep the checkboxes checked if they were checked.
I dont want the checked boxes to uncheck as I navigate from page to page. How do i achieve that?
Here is my jquery.
<script type="text/javascript">
$(document).ready(function () {
$(".header").click(function (evt) {
var sortfield = $(evt.target).data("sortfield");
if ($("#SortField").val() == sortfield)
{
if($("#SortDirection").val()=="ascending")
{
$("#SortDirection").val("descending");
}
else
{
$("#SortDirection").val("ascending");
}
}
else
{
$("#SortField").val(sortfield);
$("#SortDirection").val("ascending");
}
evt.preventDefault();
$("form").submit();
});
$(".pager").click(function (evt) {
var pageindex = $(evt.target).data("pageindex");
$("#CurrentPageIndex").val(pageindex);
evt.preventDefault();
$("form").submit();
});
});
</script>
Here is my html page
<body>
<h1>List of Customers</h1>
#{
PageSortOnlineEx.Models.SortingPagingInfo info = ViewBag.SortingPagingInfo;
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.Hidden("SortField", info.SortField)
#Html.Hidden("SortDirection", info.SortDirection)
#Html.Hidden("PageCount", info.PageCount)
#Html.Hidden("PageSize", info.PageSize)
#Html.Hidden("CurrentPageIndex", info.CurrentPageIndex)
<table border="1" cellpadding="10">
<tr>
<th>Select</th>
<th>CustomerID</th>
<th>CompanyName</th>
<th>ContactName</th>
<th>Country</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.CheckBox("select", false)</td>
<td>#item.CustomerID</td>
<td>#item.CompanyName</td>
<td>#item.ContactName</td>
<td>#item.Country</td>
</tr>
}
<tr>
<td colspan="4">
#for (var i = 0; i < info.PageCount; i++)
{
if (i == info.CurrentPageIndex)
{
<span>#(i + 1)</span>
}
else
{
#(i + 1)
}
}
</td>
</tr>
</table>
}
</body>
Here is my controller code
public ActionResult Index()
{
using (NorthwindEntities db = new NorthwindEntities())
{
SortingPagingInfo info = new SortingPagingInfo();
info.SortField = "CustomerID";
info.SortDirection = "ascending";
info.PageSize = 10;
info.PageCount = Convert.ToInt32(Math.Ceiling((double)(db.Customers.Count() / info.PageSize)));
info.CurrentPageIndex = 0;
var query = db.Customers.OrderBy(c => c.CustomerID).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(SortingPagingInfo info)
{
using (NorthwindEntities db = new NorthwindEntities())
{
IQueryable<Customer> query = null;
switch (info.SortField)
{
case "CustomerID":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CustomerID) : db.Customers.OrderByDescending(c => c.CustomerID));
break;
case "CompanyName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CompanyName) : db.Customers.OrderByDescending(c => c.CompanyName));
break;
case "ContactName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.ContactName) : db.Customers.OrderByDescending(c => c.ContactName));
break;
case "Country":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.Country) : db.Customers.OrderByDescending(c => c.Country));
break;
}
query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}

TextBoxFor not displaying value (MVC4)

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.

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???