I am currently trying to create a system that will display uploaded images(s) from a file input to a div in my view. (and have plans to add support for documents later)
The problem is that the partial view does not seem to be updating when I use an onchange function for the file input to pass the image(s) to my partial view that should be re-loaded into a div in my view and display the images.
I know that the partial view loads the first time, because of the onload function that alerts me when the div is loaded is doing nothing after the initial page load.
I know the request is being sent because when I try to perform a console.log or other actions inside the success function of the ajax call, they all work properly.
My view:
<div>
<h3>Attach File(s) (optional):</h3>
<form enctype="multipart/form-data">
<input id="fileInput" onchange="addFile()" type="file" accept="image/png, image/gif, image/jpeg, .pdf, .doc" />
</form>
<br />
<br />
<img width="750" style="display:none" id="UploadedImage" src="#" />
<div id="fileDiv">
<partial name="~/Views/Shared/_FilePreviewPartial.cshtml" />
</div>
</div>
My javascript function:
function addFile() {
var input = document.getElementById("fileInput");
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax(
{
url: "/RODispositions/UpdateFilePreview/",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
$("#fileDiv").html(data);
console.log("posted");
}
}
);
}
My partial view:
<body onload="console.log('refreshed file div')">
<div>
#foreach(var image in #Model.RODImages)
{
<img width="750" id="UploadedImage" src="#" />
<br />
Remove
}
#foreach(var document in #Model.RODDocuments)
{
Download file
<br />
Remove
}
</div>
</body>
My controller method:
[HttpPost]
public PartialViewResult UpdateFilePreviewAsync(ICollection<IFormFile> files)
{
var vm = new ViewModel()
{
RODImages = new List<byte[]>(),
RODDocuments = new List<byte[]>()
};
foreach (var file in files)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
vm.RODImages.Append(fileBytes);
}
}
}
return PartialView("_FilePreviewPartial", vm);
}
The partial is being loaded the first time that I load the page, but is not being loaded again after the ajax call. I have made similar functions that have loaded a PartialViewResult into a div with no issues before, but have no idea why this is not working. Bear in mind that I am still new to .NET programming, so any help and/or explanation would be appreciated.
The partial is being loaded the first time that I load the page, but
is not being loaded again after the ajax call.
Firstly, it should be vm.RODImages.Add(fileBytes); instead of .Append().
Then, your partial view even does not set the image src by the byte array.
Besides, it seems you want to post multiple files, be sure add multiple attribute in your input like below:
<input id="fileInput" multiple onchange="addFile()" type="file" accept="image/png, image/gif, image/jpeg, .pdf, .doc"/>
Here is a simple demo:
[HttpPost]
public PartialViewResult UpdateFilePreviewAsync(ICollection<IFormFile> files)
{
var vm = new ViewModel()
{
RODImages = new List<byte[]>(),
RODDocuments = new List<byte[]>()
};
foreach (var file in files)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
vm.RODImages.Add(fileBytes);
}
}
}
return PartialView("_FilePreviewPartial", vm);
}
Partial View:
#model ViewModel
<body onload="console.log('refreshed file div')">
<div>
#foreach(var image in #Model.RODImages)
{
//modify here...
<img width="750" id="UploadedImage" src="data:image/png;base64, #Convert.ToBase64String(image)" />
<br />
Remove
}
#foreach(var document in #Model.RODDocuments)
{
Download file
<br />
Remove
}
</div>
</body>
Note:
If your image format are all different, I think you need modify your ViewModel like below:
Model:
public class ViewModel
{
public List<RODImages> RODImages { get; set; }
public List<RODDocuments> RODDocuments { get; set; }
}
public class RODImages
{
public byte[] RODImage { get; set; }
public string Format { get; set; }
}
public class RODDocuments
{
public byte[] RODDocument { get; set; }
public string Format { get; set; }
}
Controller:
[HttpPost]
public PartialViewResult UpdateFilePreviewAsync(ICollection<IFormFile> files)
{
var vm = new ViewModel()
{
RODImages = new List<RODImages>(),
RODDocuments = new List<RODDocuments>()
};
foreach (var file in files)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
vm.RODImages.Add(new RODImages() { RODImage= fileBytes ,Format=file.ContentType});
}
}
}
return PartialView("_FilePreviewPartial", vm);
}
Partial View:
#model ViewModel
<body onload="console.log('refreshed file div')">
<div>
#foreach(var image in #Model.RODImages)
{
//modify here........
<img width="750" id="UploadedImage" src="data:#image.Format;base64, #Convert.ToBase64String(image.RODImage)" />
<br />
Remove
}
#foreach(var document in #Model.RODDocuments)
{
Download file
<br />
Remove
}
</div>
</body>
Change the Action name UpdateFilePreviewAsync to UpdateFilePreview;
[HttpPost]
public IActionResult UpdateFilePreview(ICollection<IFormFile> files)
{
var vm = new ViewModel()
{
RODImages = new List<byte[]>(),
RODDocuments = new List<byte[]>()
};
foreach (var file in files)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
vm.RODImages.Add(fileBytes);
}
}
}
return PartialView("_FilePreviewPartial", vm);
}
After doing what LajosArpad suggested and attempting to update the div to display a string in the ajax success function instead of the partial view I was trying to load, the file div did update. Meaning that the issue was with the ActionResult being passed back to the ajax success function. After going back though my controller code I found the issue to be that I had been trying to add each image to the list with the List.Append function instead of the List.Add function and that was somehow messing with the data that was returned, and changing the List.Append to List.Add allowed the partial view to be loaded properly.
Related
Snippet from my _layout.cshtml file
<body>
<!--
NAVBAR
-->
<div class="navBar">
<input id="homeButton" type="submit" name="homeButton" value="Home"/>
<input id="toolsButton" type="submit" name="toolsButton" value="Tools"/>
<input id="contactButton" type="submit" name="contactButton" value="Contact Me"/>
<input id="supportButton" type="submit" name="supportButton" value="Support"/>
<input id="aboutButton" type="submit" name="aboutButton" value="About"/>
</div><!--TODO: STYLE THESE -->
<script>
const homeButton = document.getElementById("homeButton");
const toolsButton = document.getElementById("toolsButton");
const contactButton = document.getElementById("contactButton");
const supportButton = document.getElementById("supportButton");
const aboutButton = document.getElementById("aboutButton");
homeButton.addEventListener("click", () => {
window.location.href = "/";
});
toolsButton.addEventListener("click", () => {
window.location.href = "/Tools/Index"; // "/Tools" doesn't work either
});
contactButton.addEventListener("click", () => {
window.location.href = "/";
});
supportButton.addEventListener("click", () => {
window.location.href = "/";
});
aboutButton.addEventListener("click", () => {
window.location.href = "/";
});
</script>
The error generated when button clicked
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1003: Syntax error, '>' expected
Source Error:
Line 29:
Line 30:
Line 31: public class _Page_Views_Tools_Index_cshtml : System.Web.Mvc.WebViewPage<LgbtqWebsiteNoDb.Models.Tool;> {
Line 32:
Line 33: #line hidden
Source File: c:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.0.cs Line: 31
Detailed compiler output
C:\Program Files (x86)\IIS Express> "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /t:library /utf8output /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\87f9e4d5\000e9c93_3d27cf01\System.Web.Optimization.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_global.asax.ewmqttqt.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\b5be25e0\003c87e2_1a87d401\System.Web.WebPages.Razor.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\77f8a528\001bc110_4318cf01\WebGrease.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\7a6f1e22\0016534c_1a87d401\System.Web.Razor.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\0bd5514f\8682d14f_c649d701\LgbtqWebsiteNoDb.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\5eada7ec\003c87e2_1a87d401\System.Web.WebPages.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\bfe09c51\003c87e2_1a87d401\System.Web.Helpers.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.Web.PageInspector.Loader\v4.0_1.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Web.PageInspector.Loader.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\0103d10e\00c8d184_3aaece01\Antlr3.Runtime.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\39611dac\001cbe16_536acd01\Microsoft.Web.Infrastructure.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_4.0.0.0__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activities.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\129223b9\003c87e2_1a87d401\System.Web.WebPages.Deployment.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\b4261359\00cdd33c_1a87d401\System.Web.Mvc.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll" /R:"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\assembly\dl3\dd04c433\00eff220_9da8d301\Newtonsoft.Json.dll" /out:"C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.dll" /D:DEBUG /debug+ /optimize- /w:4 /nowarn:1659;1699;1701;612;618 /warnaserror- "C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.0.cs" "C:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.1.cs"
Microsoft (R) Visual C# Compiler version 4.8.4084.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.
This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=533240
c:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.0.cs(31,106): error CS1003: Syntax error, '>' expected
c:\Users\marfx\AppData\Local\Temp\Temporary ASP.NET Files\root\ec7221e8\6a6fd7fe\App_Web_index.cshtml.f024d85f.citsmrxd.0.cs(31,106): error CS1519: Invalid token ';' in class, struct, or interface member declaration
I have tried to redirect the users to other pages via Razor with Response.Redirect("/Tools"); but this doesn't work either, throwing a different exception on the same line (compiler just picked a different character to throw on).
My Tools controller
using System.Collections.Generic;
using System.Web.Mvc;
using LgbtqWebsiteNoDb.Models;
using static LgbtqWebsiteNoDb.Models.Tool;
using Microsoft.Ajax.Utilities;
namespace LgbtqWebsiteNoDb.Controllers
{
public class ToolsController : Controller
{
private static readonly List<Tool> Tools = new List<Tool>()
{
new Tool
{
ToolName = "Hateful Countries Finder",
ReleaseDate = DateTime.Now.Date,
UpdateDate = DateTime.Now.Date, //GetLastUpdate(toolId:1), //TODO: Fix this method, it looks for the file in the wrong place
ToolId = 1,
ToolDesc = "A tool to find out which countries in the world have anti-Lgbtq+ laws which apply to you",
ToolThumbUrl = "",
ToolThumbAlt = ""
},
new Tool
{
ToolName = "Hateful Map",
ReleaseDate = DateTime.Now.Date,
UpdateDate = DateTime.Now.Date, //GetLastUpdate(toolId:2),
ToolId = 2,
ToolDesc = "A tool to show how many world countries have generic anti-Lgbtq laws",
ToolThumbUrl = "",
ToolThumbAlt = ""
}
};
public static int ToolCount = Tools.Count;
// GET: Tools/
public ActionResult Index()
{
ViewBag.Title = "Tools | Home";
return View();
}
// GET: Tools/HatefulCountriesFinder
public ActionResult HatefulCountriesFinder()
{
ViewBag.Title = "Tools | Hateful Countries";
return View();
}
// GET: Tools/HatefulMap
public ActionResult HatefulMap()
{
ViewBag.Title = "Tools | Hateful Map";
return View();
}
}
}
Tools model
public class Tool
{
/// <summary>
/// Getter and Setter for the name of a given tool
/// </summary>
public string ToolName { get; set; }
/// <summary>
/// Getter and Setter for the date the tool was released
/// </summary>
[DataType(DataType.Date)] public DateTime ReleaseDate { get; set; }
/// <summary>
/// Getter and Setter for the date the tool was last updated
/// </summary>
[DataType(DataType.Date)] public DateTime UpdateDate { get; set; }
/// <summary>
/// Getter and Setter for the tool ID
/// </summary>
public int ToolId { get; set; }
/// <summary>
/// Getter and Setter for the description of the tool
/// </summary>
public string ToolDesc { get; set; }
/// <summary>
/// Getter and Setter for the thumbnail of the tool image
/// </summary>
public string ToolThumbUrl { get; set; }
/// <summary>
/// Getter and Setter for the alt text of the thumbnail
/// </summary>
public string ToolThumbAlt { get; set; }
/// <summary>
/// Getter and Setter for the number of tools; used for enumeration
/// </summary>
public int ToolCount { get; set; }
/// <summary>
/// A method to update the tool, and change the last updated date
/// </summary>
/// <returns>DateTime</returns>
public static DateTime UpdateTool()
{
//TODO: Write the actual code for this
//TODO: Write new update DateTime to the appropriate file; See GetLastUpdate() for more
return DateTime.Now.Date;
}
}
}
Tools/Index.cshtml
#model LgbtqWebsiteNoDb.Models.Tool;
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>#ViewBag.Title</title>
<!-- Removed the bulk of the head -->
</head>
<body>
<div class="title">
</div>
<table>
#for (var i = 0; i < #Model.ToolCount; i++)
{
<tr>
<td>
<div class="toolTitle">
#Model.ToolName;
</div>
<div class="toolThumb">
<img src=#Model.ToolThumbUrl alt=#Model.ToolThumbAlt>
</div>
<div class="toolDesc">
#Model.ToolDesc;
</div>
</td>
</tr>
}
</table>
</body>
</html>
I am using .Net v4.7.2 (I would be using 5.0.0 but none of my IDEs seem to want to use the newest version, I'm on a time crunch so can't spend ages debugging that so I'm just making do)
Cheers
I'm not entirely sure but the ; at the end of the line:
#model LgbtqWebsiteNoDb.Models.Tool;
in Tools/Index.cshtml might be messing it up
to me you missed Syntax error, '>' expected for img tag in file Tools/Index.cshtml
I have a script in my header that is calling a web api which should populate a view model. This is below.
#using GigHub.Controllers
#using GigHub.ViewModel
#model GigHub.ViewModel.ProjectsViewModel
#{
ViewBag.Title = "Projects";
}
<head>
<script>
(function getProjects() {
$.get("/api/projects")
.done(function () {
alert("Got Projects");
})
.fail(function () {
alert("Something failed!");
});
});
</script>
</head>
I then have my html that would loop through the viewModel and set it up throughout the html, but every time it gets run, it is throwing a null reference exception to Model.ProjectList in the for each because it hasn't populated yet. I thought putting the script in the header would let it run first, but that doesn't seem to be the case.
<h2>Projects</h2>
<ul class="gigs voffset4" style="width: 600px;">
#foreach (var project in Model.ProjectList)
{
<li>
<div class="date">
<div class="month">
#project.Name
</div>
<div class="day">
#project.Key
</div>
</div>
<div class="details">
<span class="artist">
#project.Id
</span>
<span class="genre">
#project.ProjectTypeKey
</span>
</div>
</li>
}
</ul>
Here is my actual projectsController
public class ProjectsController : Controller
{
private readonly string m_Username = Properties.Settings.Default.username;
private readonly string m_Password = Properties.Settings.Default.password;
public ActionResult Index()
{
var client = new RestClient("https://example.net/rest/api/2/");
client.Authenticator = new HttpBasicAuthenticator(m_Username, m_Password);
var request = new RestRequest("project/", Method.GET);
request.RequestFormat = DataFormat.Json;
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = client.Execute<List<Project>>(request);
var content = response.Content; // raw content as string
if (content == null)
throw new Exception(response.ErrorMessage);
var projectArray = JsonConvert.DeserializeObject<List<Project>>(response.Content);
var viewModel = new ProjectsViewModel()
{
ProjectList = projectArray,
Heading = "Projects"
};
return View("Projects", viewModel);
}
}
You are trying to mix javascript and C# code together and expecting it to work! No. It does not work that way.
The c# code in your view ( the foreach block) gets executed by razor in the server and the resulted html markup will be send to the client browser. That means, if you are accessing Model.ProjectList in your view, you should make sure that you are passing a model to your view with that property(ProjectList).
You have 2 options.
1. Full server side approach
In your get action, create an object of your view model, set the ProjectList property and send it to view.
public ActionResult Index()
{
var vm = new YourViewModel();
vm.ProjectList= GetListOfProjectsFromSomeWhere();
return View(vm);
}
private List<ProjectItem> GetListOfProjectsFromSomeWhere()
{
var list=new List<ProjectItem>();
list.Add(new ProjectItem { Name="Project 1"}); // Replace with real data here
return list;
}
Assuming you have a view model called YourViewModel as below
public class ProjectItem
{
public string Name {set;get;}
}
public class YourViewModel
{
public List<ProjectItem> ProjectList {set;get;}
}
and
and make sure your razor view is strongly typed to this view model
#model YourViewModel
<h2>Projects</h2>
#foreach (var project in Model.ProjectList)
{
<p>#project.Name</p>
}
2. Use ajax to load page content.
From your client side code,make the call to your api(like you did) and parse the response and update the DOM.
You need to create a container element in your view so that your javascript code can append items to that from the api call result.
<ul id="projects"></ul>
Now make sure that your javscript code will execute on the document ready event.
function getProjects() {
$.get("/api/projects")
.done(function (data) {
var projectHtml="";
$.each(data,function(i,item){
projectHtml+="<li>"+item.Name+"-"+item.Key+"</li>";
});
$("#projects").html(projectHtml);
})
.fail(function () {
alert("Something failed!");
});
}
$(function(){
getProjects();
});
Assuming your api call returns an array of item, each with a Name & Key property like this
[{Name:"Project1", Key:"Pr1"},{Name:"Project2", Key:"Pr2"}]
I don't know how to use razor syntax in Javascript.
I want to make Html.ListBoxFor with items from my model. I used to use:
#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = "chzn-select", data_placeholder = "Tags..." })
As you see I want also use chzn-select class, to have better layout.
For now, I just have this code above in HTML as plain text, but I want have there things from my model.
Any ideas?
There is my code in ASP.NET MVC:
#model Generator.Models.ExamModel
#{
ViewBag.Title = "Generate";
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Multiple_chosen/chosen.jquery.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/ListOfTags.js")" type="text/javascript"></script>
<script >
$(".chzn-select").chosen();
</script>
}
<link href="#Url.Content("~/Multiple_chosen/chosen.css")" rel="stylesheet" type="text/css" />
<h1>#ViewBag.Title</h1>
<h2>#ViewBag.Message</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Generate</legend>
<div class="editor-label">Numbers</div>
<div class="editor-field" id="NumberOfModels">
#Html.EditorFor(model => model.NumberOfQuestions)
</div>
<div class="editor-label">Tags</div>
<div id="itemsmodel"></div>
<br>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
And there is javascript file:
var models = document.getElementById("NumberOfQuestions");
var modelsTable = document.getElementById("itemsmodel");
models.addEventListener("change", drawModels, false);
function drawModels() {
var modelsNum = parseInt(models.value);
var curModels = modelsTable.childElementCount;
if (modelsNum > curModels) {
var delta = modelsNum - curModels;
for (var i = 0; i < delta; i++) {
var input = document.createElement("div");
input.className = "editor-field";
input.innerHTML = "#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = \"chzn-select\", data_placeholder = \"Tags...\" })";
modelsTable.appendChild(input);
}
} else {
while (modelsTable.childElementCount > modelsNum) {
modelsTable.removeChild(modelsTable.lastChild);
}
}
}
drawModels();
My ViewModel: ExamModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ExamGenerator.Models
{
public class ExaminationModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<int> TagIdList { get; set; }
public int NumberOfQuestions { get; set; }
public string Content { get; set; }
}
}
My ActionResult Generate() in controller:
public ActionResult Generate()
{
ViewBag.Tags = new MultiSelectList(genKolEnt.TAGS, "Id", "Name", null);
return View();
}
While you can generate HTML in Javascript using Razor, if the Javascript is in an MVC view, I find that injecting into JS leads to maintenance problems. You ideally want all your JS in separate files to allow for bundling/caching and the ability to break-point the JS code (which is harder in the view).
Either inject only simple things into JS on the page, or inject elements instead.
You can inject your template Razor list into a dummy script block, so you can extract the html from it later. The type="text/template" means the browser will ignore it e.g.:
<script id="ListTemplate" type="text/template">
#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = "chzn-select", data_placeholder = "Tags..." })
</script>
The view page now looks like this (left out the irrelevant parts):
#section styles{
<link href="#Url.Content("~/Multiple_chosen/chosen.css")" rel="stylesheet" type="text/css" />
}
<h1>#ViewBag.Title</h1>
<h2>#ViewBag.Message</h2>
<script id="ListTemplate" type="text/template">
#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = "chzn-select", data_placeholder = "Tags..." })
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Generate</legend>
<div class="editor-label">Numbers</div>
<div class="editor-field" id="NumberOfModels">
#Html.EditorFor(model => model.NumberOfQuestions)
</div>
<div class="editor-label">Tags</div>
<div id="itemsmodel"></div>
<br>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Script now looks like this (jQuery version with JS as comments):
// ListOfTags.js file
// This is a shortcut DOM ready handler for $(document).ready(function(){ YOUR CODE HERE })
$(function () {
// Attach an event handler for the "change" event
$('#NumberOfQuestions').change(function () {
var $numberOfQuestions = $(this); // Convert current DOM element (the counter) to a jQuery element
var $modelsTable = $('#itemsmodel'); // document.getElementById("itemsmodel");
var modelsNum = ~~$numberOfQuestions.val(); // parseInt(models.value);
var curModels = $modelsTable.children().length; // modelsTable.childElementCount
var delta = modelsNum - curModels;
// While too few, add more
while (delta > 0) {
var $input = $('<div>').addClass('editor-field'); // document.createElement("div"); .className = "editor-field";
var template = $('#ListTemplate').html(); // Fetch the template from a script block (id="ListTemplate")
$input.html(template); // input.innerHTML =
$modelsTable.append($input); // modelsTable.appendChild(input);
delta--;
}
// While too many, remove the last
while (delta++ < 0) {
$modelsTable.children().last().remove(); // modelsTable.removeChild(modelsTable.lastChild);
}
}).change(); // Trigger an initial change event so it runs immediately
});
Notes/tips:
Place any JS in the page, at the bottom of the view, as it is easier to find. It does not matter where the #section Scripts is as the master page determines where it is injected on the final page.
Always use single quotes (') in Javascript constants by default, so that nested strings can be " which are more often required than 's. Just a good habit to get into. In fact if you had used them your code may have worked as you have added \ escaping to the quotes which will mess up the Razor processing
e.g.:
= '#Html.ListBoxFor(x => x.TagIdList, (MultiSelectList)ViewBag.Tags, new { #class = "chzn-select", data_placeholder = "Tags..." })';
If you add a #RenderSection("styles", required: false) to your master page(s) you can do the same thing for CSS as you do for scripts (ensuring all CSS is loaded in the header (for consistency). Just place them in a #section styles block.
e.g.
<head>
...
#Styles.Render("~/Content/css")
#RenderSection("styles", required: false)
...
</head>
~~ is a handy (and fast) alternative to parseInt to convert values to integers.
Use $ as a prefix for jQuery object variables. This makes it easier to remember when to use jQuery methods vs DOM properties.
Test controller code:
private MultiSelectList TagList()
{
var items = new List<KeyValuePair<int, string>>() {
new KeyValuePair<int, string>(1, "MVC"),
new KeyValuePair<int, string>(2, "jQuery"),
new KeyValuePair<int, string>(3, "JS"),
new KeyValuePair<int, string>(4, "C#"),
new KeyValuePair<int, string>(5, "PHP")
};
MultiSelectList list = new MultiSelectList(items, "key", "value", null);
return list;
}
// Get request starts with one list
public ActionResult Test()
{
ExamModel vm = new ExamModel()
{
NumberOfQuestions = 1,
TagIdList = new List<int>()
};
ViewBag.Tags = TagList();
return View(vm);
}
[HttpPost]
public ActionResult Test(ExamModel model)
{
ViewBag.Tags = TagList();
return View(model);
}
If it's a static JavaScript file and you are not generating it dynamically with razor view engine It won't work because in this case there is no processing performed on a server side. It is the same as accessing static html page/css file/image and etc...
On the other hand if this JavaScript is part of some Razor view, which means that it gets rendered by razor view engine, when you have return View() (or anything like that) in your controller action, than this code should work.
The problem is, java script files are not processed by server, so you won't be able to insert anything in those using ASP.NET MVC. Razor files on the other hand are processed on server so you can insert data into those (either through view bag or model).
One way is:
.cshtml:
<script>
var someVariable = '#model.data';
</script>
then use this variable in your javascript file:
function someFunction(){
var myData = window.someVariable;
}
The other way is to have all javascript in .cshtml file and render it as a partial view.
#Html.Partial("Path/to/javascript/in/razor/view")
edit: seeing your code, this will not help you very much.
If you want to dynamically add/remove dom elements, you will have to do it with javascript: either generate them with "document.createElement()" or load them via ajax if you want some server side processing.
#Html.ListBoxFor
is a server side helper that generates tag and fills it up depending on the parameters. You can do that with javascript as well.
I am using ASP.NET MVC 4 to develop a web application. I have an external javascript file which contains a method initializeLocation(). If I reference the file in the Index view of my Home controller it works fine. But when I try to reference the JS file in another view, and call the method in the body onLoad, then I get the following error:
Uncaught ReferenceError: initializeLocation is not defined
Here is the code of my view:
#{
ViewBag.Title = "Online Users";
}
<html>
<head>
<title>Online Users</title>
</head>
<body onload="initializeLocation()">
<h2>Online Users</h2>
<div id="wrapper">
<div id="upperPanel">
<div>
<ul id="onlineUsers" itemid="#HttpContext.Current.User.Identity.Name">
</ul>
</div>
<div id="friends">
</div>
</div>
<div id="bottomPanel">
<input id="submitLocation" type="submit" value="Share Location" style="margin-left: 10px;" /><br />
</div>
</div>
<label id="locLabel"></label>
<div id="map" style="width: 100%; height: 600px"></div>
<script>
var Pusher_APP_KEY = 'b5ee1a1486b7f0cec06f';
</script>
<script src="http://js.pusher.com/1.12/pusher.min.js"></script>
<script src="~/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBsjVTOfgW39medqXn6cmOTfVyyxIX3Nl8&sensor=true"> </script>
<script type="text/javascript">
//postURL is used in locationFinder.js to set the URL of POST requests
//It is declared here to be able to use a separate java file instead of embedding it
var postURL = '#Url.Action("Index", "Home")';
</script>
<script type="text/javascript" src="~/Scripts/locationFinder.js">
</script>
</body>
</html>
And here is my controller code:
namespace LBSPrototype1.Controllers
{
public class HomeController : Controller
{
private static readonly PusherProvider Provider = new PusherProvider
(
ConfigurationManager.AppSettings["pusher_app_id"],
ConfigurationManager.AppSettings["pusher_key"],
ConfigurationManager.AppSettings["pusher_secret"]
);
public ActionResult Index(string latitude, string longitude, string username)
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//
// GET: /Home/OnlineUsers
[AllowAnonymous]
public ActionResult OnlineUsers()
{
return View();
}
//
// POST: /Home/OnlineUsers
[AllowAnonymous]
[HttpPost]
public ActionResult OnlineUsers(string latitude, string longitude, string username)
{
var now = DateTime.UtcNow;
var request = new ObjectPusherRequest(
"chat_channel",
"message_received",
new
{
lat = latitude,
lon = longitude,
user = username,
timestamp = now.ToShortDateString() + " " + now.ToShortTimeString()
});
Provider.Trigger(request);
return View();
}
}
}
I'm new to MVC and am still getting used to the concept of controllers and such, but can't see why the exact same code should work in one view and not the other.
Instead of
<script src="~/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript" src="~/Scripts/locationFinder.js"></script>
Use
<script src="#Url.Content("~/Scripts/jquery-1.8.2.js")" type="text/javascript"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/locationFinder.js")" ></script>
The problem is the url which is render on the page. use #Url.Content to render a url with its rool path reference. it will render correct url while in routing.
I have a HTML page in which I have a button; pressing that button a javascript function is called - here results a String which is the representation of an xml. I want to represent this xml on the same page with the button, similar with what is in the picture below:!
Here is the simplified code I've tried but did not worked (see under the code the result of it - nothing displayed):
<html>
<head>
<script type="text/javascript">
function xml_test()
{
var xmlString = "<note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var my_div = document.getElementById("labelId");
alert(xmlString)
my_div.innerHTML += xmlString;
}
</script>
</head>
<body>
<input type="button" value="TEST" onclick="xml_test()"/>
<br><br>
<label id="labelId">XML: </label>
</body>
</html>
I've tried with an iframe also, but I do not have an file for the src attribute.
What I've tried is:
<html>
<head>
<script type="text/javascript">
function populateIframe() {
var xml = "<?xml version='1.0' encoding='UTF8' standalone='yes'?><note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var iframe = document.getElementById('myIframe');
var idoc= iframe.contentDocument || iframe.contentWindow.document; // IE compat
idoc.open("text/xml"); // I know idoc.open(); exists but about idoc.open("text/xml"); I'm not sure if exists;
idoc.write('<textarea name="xml" rows="5" cols="60"></textarea>');
//idoc.write(xml); // doesn't work
idoc.getElementsByTagName('textarea')[0].value= xml;
idoc.close();
}
</script>
</head>
<body onload="populateIframe();">
<iframe id="myIframe" width="900" height="400"></iframe>
</body>
</html>
and the result is:
I've already looked over How to display XML in a HTML page as a collapsible and expandable tree using Javascript?
I took some ideas from here
Thank you for helping me!
Just Create am HttpHandler, and open it in a Iframe:
public class Handler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
XmlSerializer serializer = new XmlSerializer(typeof(Note));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.Unicode);
serializer.Serialize(writer, new Note() { Name = "Kundan Sinha", Place = "Bangalore", State = "Karnataka" });
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding();
stream.Close();
writer.Close();
context.Response.ContentType = "text/xml;charset=utf-8";
context.Response.Write(utf.GetString(arr).Trim());
context.Response.Flush();
}
#endregion
}
public class Note
{
public string Name { get; set; }
public string Place { get; set; }
public string State { get; set; }
}
You can pass your received xml string to this where I am doing
context.Response.Write('Pass you XML data here');
You must use your favorite JavaScript library with a tree widget to display that XML in tree form.
Note that the "tree-like" view you see is actually IE's default view for XML files. Other browsers will have different views for XML files, and some do not even let you view XML files without a plug-in.
You should not depend on browser-specific functionality if viewing the XML in tree form is important to your page's functionality.
If you, however, just want to press a button and then the whole page gets turned into an XML, then by all means just redirect to that XML URI on button press. IE will show that XML file in tree form, while other browsers may either ask you to download the file, or display the XML file in whatever format that is determined by their plugin's.
I set the xml data in the src attribute:
iframeElement.setAttribute('src', 'data:text/xml,<test>data</test>');