ASP - Master Page and User Controls - html

I'm currently trying to use a UserControl in my master page; however my ascx file doesn't like my code, two parts specifically:
#Html (Doesn't exist in current context)
Model. (Doesn't exist in current context)
.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ConveyancingUserControl.ascx.cs" Inherits="xxx.Controllers.ConveyancingUserControl" %>
<div id="cwContainer" class="ui-widget-content">
<div id="cwHead">
<p class="cwhTitle">Conveyancing Quotation</p>
</div>
<div id="cwBody">
<%using (Html.BeginForm("Home", "Xxxx", FormMethod.Post, new { onsubmit = "document.getElementById('xxxxBusy').style.display = 'inline';", #class = "xxxxForm" }))
{%>
<table>
<tr>
<td>What are you doing?</td>
<td> <%: #Html.DropDownListFor(Quote => Model.sessionQuote.quoteType, Model.sessionQuote.quoteTypeList, new { style = "width:150px" })%> </td>
</tr>
</table>
<%} %>
</div>
<div id="cwFoot"></div>
</div>
ascx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mvc;
namespace ASP4HFWClaimsPortal.Controllers
{
public partial class ConveyancingUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
.Master:
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<xxx.Models.XxxxSession>" %>
<!-- The main body of each page -->
<div id="MainBody" runat="server" >
<ul class="xxxxMenu">
<li class="xx"> <%: Html.ActionLink("Home", "Home", "x", null, new { onclick="document.getElementById('xx').style.display = 'inline';", #class="x", #title="Home" })%></li>
<li class="x"> <%: Html.ActionLink("About", "About", "Xxxx", null, new { onclick="document.getElementById('xx').style.display = 'inline';", #class="x", #title="About" })%></li>
</ul>
<section class="content-wrapper main-content clear-fix">
<!-- Additional BODY content for each individual page is inserted here -->
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</section>
<uc1:conveyancingusercontrol ID="ConveyancingUserControl1" runat="server" />
</div>
Web.config:
<controls>
<add src="~/Controllers/ConveyancingUserControl.ascx" tagName="ConveyancingUserControl" tagPrefix="uc1"/>
</controls>
I realise that my ascx file needs some kind of reference to find my model I'm just not sure how to do this... or if it's even possible. With regards to the 'Html.' issue, I guess this is something similar.
Apologies if these are silly questions... ASP seems to be one of those skills i jump into every now and again so I never get time to really explore it.

#Html is Razor syntax. You need to use the <%, <: etc syntax for ASP.
Model exists in MVC, you need to look at code-behind to populate your controls.

Related

How to assign an div id a variable without using Javascript?

I'm trying to create multiple divs inside a for loop on a jsp page. I'm loading all the posts in a forum from a database, each one being a new div. I'm trying to make divs having id like id= "post-" + title, where title is a variable.
I tried with this way of puting out.printlnt(title) and is not working, I also found a solution saying to put smth like div id = {{title}} that still didn't work. Do you know if is possible to do this without using javascript? I just want to assign the id from the for loop.
for (ForumPost fp : allForumPosts) {
//get title and likes variables
<div id = "<%out.println(title);%>" >
<%out.println(title); out.println(likes);%>
<a>LIKE</a>
</div>
}
If you don't mind using jstl (which is preferred way to scriptlets) you can do this the following way:
<c:forEach var="post" items="${allForumPosts}">
<div id="post-${post.title}">
${post.title}; ${post.likes} <a>LIKE</a>
</div>
</c:forEach>
Just make sure to include this tag at the top of your jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
If you want to use scriptlets as you do now, I think you should do something like:
<% for (ForumPost fp : allForumPosts) {%>
<div id="post-<%out.write(fp.title)%>">
<%out.write(fp.title)%>;<%out.write(fp.likes)%>
<a>LIKE</a>
</div>
<% } %>
But you really should consider using jstl instead of scriptlets
Java Server Pages (JSP) is a server-side programming technology for your front-end.
Assuming that you have passed the object from your controller to JSP, then you can achieve the desired for loop with JSTL
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${allForumPosts}" var="post">
<div id="post-${post.title}"></div>
</c:forEach>
If you however prefer scriptlet (not recommended), here is how it's done
<% for (ForumPost post : allForumPosts) { %>
<div id="post-<%=post.title%>"></div>
<% } %>

Render data from database in layout file

I want to include data (fetching from a database) in the _layout file of my asp.net mvc core project.
Situation:
_Layout page
#if (SignInManager.IsSignedIn(User))
{
Html.Action("Modules", "Layout")
}
Controllers/LayoutController.cs
using Microsoft.AspNetCore.Mvc;
namespace project.Controllers
{
public class LayoutController : Controller
{
...
public ActionResult Modules()
{
///Return all the modules
return PartialView("_Modules", moduleAccess.ToList());
}
}
}
Views/Shared/_Modules.cshtml
#model IEnumerable<project.Models.Module>
<div class="two wide column">
<div class="ui menu" id="modules">
#foreach (var item in Model)
{
<a class="item">
#Html.DisplayFor(modelItem => item.Name)
</a>
}
</div>
When going the webpage I get the following error:
'IHtmlHelper<dynamic>' does not contain a definition for 'Action' and the best extension method overload 'UrlHelperExtensions.Action(IUrlHelper, string, object)' requires a receiver of type 'IUrlHelper'
What am I doing wrong? How can I get the data in the layout page?
In ASP.NET Core instead of Html.Action use View Components: #await Component.InvoceAsync.
You can still use #await Html.RenderPariantAsync and pass there some data from the model if you want.
Solution with view components
ViewComponents/ModuleListViewComponent.cs
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace ViewComponents
{
public class ModuleListViewComponent : ViewComponent
{
...
public async Task<IViewComponentResult> InvokeAsync()
{
return View(moduleAccess.ToList());
}
}
}
Views/Shared/Components/ModuleList/Default.cshtml
#model IEnumerable<project.Models.AdminModels.Module>
<div class="two wide column">
<div class="ui left vertical labeled icon menu stackable" id="modules">
#foreach (var module in Model)
{
<a class="item">
#module.Name
</a>
}
</div>
</div>
Views/Shared/_Layout.cshtml
#if (SignInManager.IsSignedIn(User))
{
#await Component.InvokeAsync("ModuleList")
}

Update HTML tag in the view with Ajax dilemma

I'm new to this and have no idea how it must work.
I have a partial view in a foreach in my view that lists all news comments for that news article.
I have a textarea with a post button where the user can submit further comments on this news article.
The new news article must be appended to the list, without doing a location.reload. I was told do use AJAX, not JSON.
Here's my controller:
[HttpGet]
[NoCache]
public ActionResult SetCommentOnNews(int newsId, string newsComment) ??
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.SetCommentOnNews(newsId, newsComment, currentUser.UserId);
return Json(new { success = true }, JsonRequestBehavior.AllowGet); ??
}
<div class="news-comment-content" id="news-comment-content">
<% if (Model.Results != null) {
foreach (var newsItem in Model.Results.NewsComments) %>
<% { %>
<% Html.RenderPartial("~/Views/Home/SetCommentOnNews.ascx", newsItem); %>
<% } %>
</div>
my partial:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Zinc.Web.Areas.News.ViewModels.Home.NewsCommentsViewModel>" %> //this also not right
<div class="news-post-list-item">
<div class="news-post-user-info-wrapper">
<div class="avatar">
<img width="52" height="52" alt="Avatar" src="/ThemeFiles/Base/images/User/user-avatar.png"/>
</div>
<div class="who-and-when-box">
<%: newsItem.CommentDate %>
<br />
<br />
<%: ViewBag.UserName %>
</div>
<div class="news-comment"><%: newsItem.NewsComment %></div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="header">
<h3>
Leave a comment
</h3>
</div>
<div>
<textarea id="textareaforreply" rows="3" cols="160"></textarea>
</div>
<div>
Post
</div>
<script type="text/javascript">
function PostNewsComment(newsId) {
$("post-button").click(function () {
var jqxhr = $.getJSON("<%= //Url.Action("SetCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").text(), function (data) {
if (data.success) {
alert($("#textareaforreply").text());
$('#news-comment').append($("#textareaforreply").text());
}
});
}
</script>
The above JS is what I have and must inject HTML in to the list using AJAX?
I have NO idea how to do this. Can some one help please?
Thanks
To inject HTML into a list using AJAX I would use Knockoutjs with templates instead of partial views. Knockout can be used to render the information in the browser. Views are for rendering server side, which does not jibe well with AJAX.
What do you mean when you say, "I was told do use AJAX, not JSON". AJAX uses JSON as a method for serializing the data that is sent over the network. Are you referring to the JQuery methods ajax versus getJSON? getJSON is just a wrapper around the ajax method that configures it specifically to retrieve JSON using the HTTP GET verb. Either will work fine, but ajax does give you more control in configuring the request.

PartialViews - Not Using Shared Site.css in Editor/Display Templates - ASP.NET MVC 3

I'm using the JQuery UI Tabs functionality in my Open Source Project. I'm doing this to learn MVC3 (And various other technologies). Now I've got that all working. The problem is my Partial Views within each tab have links off the the relevant CRUD functionality. I've set these CRUD views up as Display and Editor Templates. Its these that are not picking up the _Layout.cshtml references to the Site.css.
EDIT START
I've found in the "Add View" scaffolding functionality that when you click the Create as a partial view box that the master page functionality disappears, ie greys out, BUT in Razor I thought if this is empty it uses the _viewstart file, which loads the_Layout?
EDIT END
Here is my Dashboard.cshtml code with the JQuery UI Tab logic:
<script type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs();
getContentTab (1);
});
function getContentTab(index) {
var url='#Url.Content("~/SiteAdmin/AjaxGetTab")/' + index;
var targetDiv = "#tabs-" + index;
var ajaxLoading = "<img id='ajax-loader' src='#Url.Content("~/Content")/ajax- loader.gif' align='left' height='28' width='28'>";
$(targetDiv).html("<p>" + ajaxLoading + " Loading...</p>");
$.ajax({
type: 'get',
url: url,
cache: false,
success: function(result) {
$(targetDiv).html(result);
}
});
}
<div id="tabs">
<ul>
<li>Transaction Type </li>
<li>Direction Type</li>
<li>User Type</li>
<li>Currency Type</li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
<div id="tabs-4">
</div>
</div>
Here is my AjaxGetTab Action Method if you need to know how i decide to create tabs and create the list objects:
/// <summary>
/// AJAX action method to obtain the correct Tab to use.
/// </summary>
/// <param name="index">Tab number</param>
/// <returns>Partial View</returns>
public ActionResult AjaxGetTab(int id)
{
string partialViewName = string.Empty;
object model = null;
//--Decide which view and model to pass back.
switch (id)
{
case 1:
partialViewName = "_TransactionType";
model = db.TransactionTypes.ToList();
break;
case 2:
partialViewName = "_DirectionType";
model = db.DirectionTypes.ToList();
break;
case 3:
partialViewName = "_UserType";
model = db.UserTypes.ToList();
break;
case 4:
partialViewName = "_CurrencyType";
model = db.CurrencyTypes.ToList();
break;
case 5:
partialViewName = "_tabError";
break;
}
return PartialView(partialViewName,model);
}
At the moment I'm working on TransactionType so here is the _TransctionType.cshtml code for the PartialView:
#model IEnumerable<Accounts.Models.TransactionType>
<p>
#Html.ActionLink("Create New", "CreateTransactionType")
</p>
<table>
<tr>
<th>
Record Status
</th>
<th>
Description
</th>
<th>
Created Date
</th>
<th>
Amended Date
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.RecordStatus)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.AmendedDate)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.id }) |
#Html.ActionLink("Details", "Details", new { id=item.id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.id })
</td>
</tr>
}
Now the "Edit" & Delete ActionLink has an EditorTemplate and the Details has a DisplayTemplate folder with the required TransactionType.cshtml Its these views which the _Layout Site.css isnt being applied to. Here is example code from the "Edit" code base:
_EditTransactionType.cshtml:
#model Accounts.Models.TransactionType
#using (Html.BeginForm())
{
#Html.EditorForModel()
<p>
<input type="submit" value="Save" />
</p>
}
And here is the TransactionType.cshtml which sits in /Views/SiteAdmin/EditorTemplate:
#model Accounts.Models.TransactionType
<fieldset>
<legend>Transaction Type</legend>
<div class="editor-label">
#Html.LabelFor(model => model.RecordStatus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RecordStatus)
#Html.ValidationMessageFor(model => model.RecordStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
</fieldset>
Now I could just put a reference to the Site.css in each Template, but is there a cleaner way of doing this? Am I missing something?
_ViewStart is only applied to Views that are rendered, this is determined on how you render the view. E.G using RenderPartial or returning a PartialView from a controller returns only the contents (and nest partials) of the PartialView that you are targetting.
If the _LayoutFile applied to every view and every partial view then you would end up with pages like so:
<html>
<head />
<body>
<html>
<head />
<body>
<!-- Actual Partial View Content -->
</body>
</html>
</body>
</html>
When a page is rendered all of the the _layout, the view to be rendered, any partial views and any nest partials or editor/display templates are built into a single page and returned to the client so any style sheets that are referenced by the _Layout master will be applied to this now flattened heirarchy of (Partial)Views.
Have you inspected the output HTML to make sure that is as expected? It may not be a problem with the views.
I really don't see why you complicated using jqueryui tabs so much adding onclick then a switch etc.
<div id="tabs">
<ul>
<li><span>Transaction Type</span></li>
<li><span>Direction Type</span></li>
<li><span>User Type</span></li>
<li><span>Currency Type</span></li>
</ul>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#tabs').tabs({
spinner: '<img src="../../Content/Images/tabsppinner.gif" alt="" /> #Loading...'
});
});
</script>
Then you would just have one controller with actions defined for every tab.

returning data from checkboxes in mvc 2 view

I'm using checkboxes in the view of my MVC2 project to allow users to select multiple objects. Here is the code in my view(skipping unrelated lines:
<h2>Install New Equipment</h2>
//Html.BeginForm("CreateRequest1", "Home", FormMethod.Post);
<div>Employee's First Name: <%= Model.Employee.EmpFName%></div>
<div>Employee's Last Name: <%= Model.Employee.EmpLName%></div>
<div>Employee's Phone Number: <%= Model.Employee.Phone%> </div>
<br />
<div>Please select the equipment you would like to request:</div><br />
<div> <% foreach (var info in ViewData.Model.EquipDescription)
{ %>
<% = Html.CheckBox("Description", info.ID) %><%=info.Description%> <br />
<%} %>
</div><br />
<div>Please Select the Location for the Equipment to be Installed </div><br />
<div>Building <%= Html.DropDownList("NewBuildings", new SelectList((IEnumerable)ViewData["buildings"], "ID", "Buildings")) %>
Floor <%= Html.DropDownList("NewFloors", new SelectList((IEnumerable)ViewData["floors"], "ID", "FloorNumber")) %>
Office<%= Html.DropDownList("NewOffices", new SelectList((IEnumerable)ViewData["offices"], "ID", "OfficeNumber")) %>
</div>
<br />
<div>Comments: <%=Html.TextArea("Comments") %></div><br />
<%Html.EndForm(); %>
(I removed the <%%> around the begin form line so my whole post would show)
Everything display perfectly in the view. I recieve all the other data from the user. I just don't know how to recieve the data from the selected checkboxes
[HttpPost]
public ActionResult CreateRequest1(int NewBuildings, int NewFloors, int NewOffices, string comments, int[] Description)
What should I add here to get the selected values?
You'll need to add a parameter to your method like:
[HttpPost]
public ActionResult CreateRequest1(int NewBuildings, int NewFloors, int NewOffices, string comments, ICollection Description)
I assume your value is an int, but you can change it if required.
You can read more here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx