mvc3 create link from controller - asp.net-mvc-3

Is there a way to create a link from a controller and apppend it to a ViewBag ? I been trying but nothing is working
HyperLink hyperl = new HyperLink();
hyperl.NavigateUrl = "http://www.example.com/";
hyperl.Text = "Here is why..";
ViewBag.check ="You must register"+ hyperl;
You must register System.Web.UI.WebControls.HyperLink
I know that I am probably only missing 1 more line but i can't find it..

You could use the TagBuilder and do something like
public static TagBuilder CreateAnchor(string text, string url)
{
var anchor = new TagBuilder("a");
anchor.SetInnerText(text);
anchor.MergeAttribute("href", url);
return anchor;
}
Then pass to the ViewBag Like this
ViewBag.hyperl = CreateAnchor("Here is why..","http://www.example.com/");

You're mixing web forms with MVC. The result will be an abomination. Just send the URL through the view bag, and use it in the markup in a plain anchor tag:
Controller code:
ViewBag.LinkAddress = "...";
Markup:
Link

Try this
in Controller
HyperLink hyperl = new HyperLink();
hyperl.NavigateUrl = "http://www.example.com/";
hyperl.Text = "Here is why..";
ViewBag.check = hyperl.NavigateUrl;
ViewBag.Text = "You must register";
in View
<a href=#ViewBag.check>#ViewBag.text</a>
or
<a href=#ViewBag.check>You must register</a>

Related

How to display a fully formed HTML page as an MVC view?

MVC/ASP.NET/C#/html/javascript newbie question:
I'm trying to move some legacy software into an MVC solution. I have an MVC controller ViewResult method that makes an API call to the legacy system and returns a string which is a fully formed HTML page (including the HTML start and end tags). Some time in the future, I'll rewrite the logic as an MVC view, but for right now I need to just display that page (preferably in a new tab).
I've tried this in the controller:
return View((object)calendar);
(where "calendar" is the string containing the HTML document)
In my view I have
#model string
#{ Layout = null; }
#Model
But that didn't work.
Any ideas?
Model binding is binding the object of your model class.
For example, ([Solution].[Models].[Model class]),
#model PassDatainMVC.Models.Record
To pass the data from controller to view,
Approach 1: ViewBag
Controller:
string data = "testing";
ViewBag.see = data;
return View();
View:
#using PassDatainMVC.Models
#ViewBag.see
Or:
Approach 2: Model binding
Controller (Class):
public string recordProperty;
View:
#model PassDatainMVC.Models.Record
#Model.recordProperty
While you have to set the property under the model class in the data field for the second approach.
Ref. https://www.c-sharpcorner.com/article/asp-net-mvc-passing-data-from-controller-to-view/
If you want to just one data you can use a ViewBag. This is simple.
Also you want to send with model. You should use this code.
Class
public class Calendar
{
public string CalendarName { get; set; }
}
Controller
Calendar newModel = new Calendar();
newModel.CalendarName = "test name...";
return View(newModel);
View
#model ModelNamespace.Calendar
<h1> #Model.CalendarName </h1>
Thanks Reha! But unfortunately neither of your suggestions did the trick.
For your first suggestion I used ViewBag. In the controller I replaced
return View((object)calendar);
to
ViewBag.calendar = calendar;
return View();
And replaced the view with just
#{ Layout = null; }
#ViewBag.calendar
The result was that the user is left looking at the actual HTML code instead of what the HTML code is supposed to render.
For your 2nd suggestion, I did exactly as you suggested (except I changed
Model.CalendarName = "test name...";
to
Model.CalendarName = calendar;
The result is the same, the user is left looking at the HTML code.

display the selected value from DropDown in a page

Hi Folks i am retrieving Name from database to drop down list. Now i want to display the selected value from DropDown in a page. My code is like follows to retrieve data,am using Fluent data as a framework.
My Controller Action is
var query = Abc.GetProducts();
ViewBag.EnterpriseId = new SelectList(query.AsEnumerable(), "EnterpriseId", "Name");
return View();
My view is ,
#Html.DropDownList("EnterpriseID", (SelectList) ViewBag.EnterpriseID, "--Select Resource--")
You can use a simple js for this:
elem = $('.selectClass');
options = elem.find('option[value="'+DataFromDBHere+'"]');
if(options){
options.prop('selected', 'selected');
}

MVC3 Parent Child Views

I want to create a layout like the User page on Stack Overflow where there is a view (the parent view) at the top of the page and then content in tabs, each with it's own view (child views).
When I hover over each of the tabs on the User page in SO it looks like they are pointed at the user controller and are being sent the tab name in the query string to render the appropriate tab content.
I believe I can achieve this using a layout with a section defined in the parent view. The section would be the child view, but I don't know how I would tell the section which view or partial view to show.
I have not been able to find anything useful on the web. Can someone tell me how to do this or at least point me in the right direction?
Thanks in advance!
Edit: Thanks to #Mystere's help I was able to come up with the solution below in case anyone else is trying to do the same thing.
HTH
Final Solution:
Controller Actions
public ActionResult Details(int id, string tab = null)
{
ViewBag.Jobid = id;
ViewBag.Tab = tab ?? "Services";
var viewModel = getJobRecordDetails(id);
return View(viewModel);
}
public ActionResult JobInfo(int id, string tab)
{
ViewBag.Jobid = id;
ViewBag.Tab = tab;
if (tab == "Services")
{
var viewModel = getServices(id);
return View("Services", viewModel);
}
if (tab == "Equipment")
{
var viewModel = getEquipment(id);
return View("Equipment", viewModel);
}
if (tab == "Personnel")
{
var viewModel = getPersonnel(id);
return View("Personnel", viewModel);
}
return View("Error");
}
Parent View
#model MyApplication.Models.JobViewModel
#{
ViewBag.Title = "Details";
}
<h2>Job Details</h2>
...
#* Child View Action *#
#Html.Action("JobInfo", new { id = ViewBag.Jobid, tab = ViewBag.Tab })
Child View
#model MyApplication.Models.ServicesViewModel[]
#{
ViewBag.Title = "Services";
Layout = null;
}
#* Submenu Navigation *#
#{
Html.RenderPartial("SubMenu");
}
<h2>Services</h2>
Services here...
Subnavigation Partial View
<div id="submenucontainer">
<ul id="submenu">
<li class="#Html.ActiveTab("Job","JobInfo","Services")">Services </li>
<li class="#Html.ActiveTab("Job","JobInfo","Equipment")">Equipment</li>
<li class="#Html.ActiveTab("Job","JobInfo","Personnel")">Personnel</li>
</ul>
ActiveTab Helper
public static string ActiveTab(this HtmlHelper helper, string controller, string action, string tab)
{
var classValue = "";
var currentController =
helper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
var currentAction =
helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
var currentTab = helper.ViewContext.Controller.ValueProvider.GetValue("tab").RawValue.ToString();
if (currentController == controller && currentAction == action && currentTab == tab)
classValue = "selected";
return classValue;
}
It is unlikely they are using a section for that. sections are used primarily in layout pages (the equivelent of master pages).
More than likely, they just have multiple views, and they pass whichever view is appropriate to the View() method. They might use partial views, or MVC templates to render the tab areas, so that common code is factored out.
Edit:
As requested, code sample:
In action method:
public ActionResult Dashboard(string tab) {
if (tab == "summary")
ViewBag.Tab = "~/Views/Dashboard/Summary.cshtml";
if (tab == "activity")
ViewBag.Tab = "~/Views/Dashboard/Activity.cshtml";
return View()
}
in Dashboard.cshmtl
... your parent view
#Html.Partial(ViewBag.Tab)
... your footer
It's not rocket science. There are so many ways to do this it doesn't take much thought to come up with one of them.

MVC3 Helper DisplayFor Model

I've got a view that displays a list of items. Rather than display items in a grid, I'd like to display 4 items per page, each with an image and multiple properties, displayed in a unique layout.
So, I'd like a foreach to iterate through the items, and each item to get displayed in a div. I could put all the code in the loop, but I'd like to have a custom html helper extension to do this.
I came up with this,
public static MvcHtmlString DisplayViewerFor(this HtmlHelper helper, TestModel model, bool rightAligned = true) {
if (model == null) {
model = new TestModel();
}
var outterDiv = new TagBuilder("div");
outterDiv.AddCssClass(rightAligned ? "item-display-right" : "item-display");
var image = new TagBuilder("image");
image.Attributes.Add("src", "Item/GetImage/" + model.ItemName);
image.Attributes.Add("height", "150");
var editorLabel = new TagBuilder("div");
editorLabel.AddCssClass("editor-label");
//LOOKING TO ADD CODE LIKE THIS HERE
var labelContent= html.LabelFor({my model property here})
editorLabel.InnerHtml += labelContent;
//END OF ADD
return new MvcHtmlString(outterDiv.ToString(TagRenderMode.EndTag));
}
In my method above, I need to display a few more values, and I would like to use the Html.LabelFor and Html.DisplayFor helpers, but the methods aren't available and I'm not sure what to pass to them if they were.
I'm not sure if this is possible or not, but I thought I would ask.
EDIT
I'm trying to use the html.LabelFor. See my code where I have updated it above, adding to it these two lines.
var labelContent= html.LabelFor({my model property here})
editorLabel.InnerHtml += labelContent;
You can see the code above.
EDIT 2
Here is the planned use for this Helper with dummied down view.
#model TestItemDisplayList
#{
ViewBag.Title = "Items";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#foreach(var item in #model.Items){
#Html.DisplayViewerFor(item)
}
You can use the Html.DisplayFor method to render a DisplayTemplate. One of the over loads for the method is to specify a template to use. You can modify your page code to read:
Page:
#model TestItemDisplayList
#{ ViewBag.Title = "Items"; Layout = "~/Views/Shared/_Layout.cshtml"; }
#Html.DisplayFor(model => Model,"TestItemDisplayList")
Display Template for TestItemDisplayList
#model TestItemDisplayList
#* You could limit this loop to the first 4 items *#
#foreach(var item in model.Items){ #Html.DisplayFor(item => item) }
Display Template for TestModel
#model TestModel
<div class="item-display">
<img src="#Url.Action("GetImage", "Image", new { id = Model.ItemName})" height="150"/>
<div class="editor-label">#Html.LabelFor(model => model.PropertyHere)</div>
</div>
I assume that your URL for the image used the default route of {controller}/{action}/{id} so I used the Url.Action and specified your ID.
You could also get away witout using a DisplayTemplate for "TestItemDisplayList" and moving that code in to your page but I wasn't clear if you wanted to add logic in that to limit the number of pages.

ASP.NET MVC3 - Pagination Only (No WebGrid to be Displayed)

I'm seeking to display my images with a short title in a flow from left to right as opposed to the gridview that is a sequential layout. I desire to use the pagination that the webgrid provides so as not to recreate the wheel, as it were.
I've reviewed Leek's blog post (http://msdn.microsoft.com/en-gb/magazine/hh288075.aspx) and Broer's (http://blog.bekijkhet.com/2011/03/mvc3-webgrid-html-helper-paging.html) to ensure I have a solid introduction to the use of the webgrid but I'm falling short on how to apply the pagination without using the traditional layout of the webgrid.
I am using the Razor layouts.
Ideas or thoughts?
My controller is currently:
public ActionResult Index(string cid)
{
Catalog item = new Catalog();
item.objConnection.Open();
OdbcDataReader reader = item.getCatalogItems(cid, 3);
List<Catalog> listItems = new List<Catalog>();
while (reader.Read())
{
Catalog i = new Catalog();
i.kitName = reader.GetValue(1).ToString();
i.catalogID = reader.GetValue(0).ToString();
ViewBag.CatalogName = reader.GetValue(0).ToString(); //TODO: change this to name once in place
listItems.Add(i);
}
ViewBag.ItemsPerCatagory = listItems.Count;
reader.Close();
item.objConnection.Close();
return View(listItems);
}
My View:
#model IEnumerable<MvcApplication1.Models.Catalog>
#{
ViewBag.Title = ViewBag.CatalogName;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.CatalogName (#ViewBag.ItemsPerCatagory) Items Available</h2>
<p>
Category will have a brief description here for seo purposes.
</p>
<p>
#foreach (var catalog in Model)
{
string imageUrl = "http://web3.naeir.org/images/Specials/" + #catalog.kitName + ".JPG";
<img src=#imageUrl height="150px" width="150px" /> #Html.ActionLink(#catalog.kitName, "Details", "Product", new { cid = #catalog.catalogID, itemid = #catalog.kitName }, null)
}
</p>
Upon much hacking at my code I found that a simple option exist and my solution was to use MVCPager MVC Pager Website
I was able to simply download it via VS Web Developer Express Package Manager NuGet, read the documentation and implemented the code. Pretty straight forward.

Resources