I am creating an MCQ page and I am stuck at a point. when I upload image's for different MCQs. On upload same image save for all MCQs.
Please don't mind if I miss something to define. I am new on Stack and also on blazor.
<SfUploader ID="UploadFilesMCQ" AllowedExtensions=".png,.jpeg,.jpg" >
<UploaderEvents ValueChange="onChangeMCQ" OnRemove="onRemoveMCQ"></UploaderEvents>
<UploaderTemplates>
<Template Context="HttpContext">
<td>
<img class="upload-image" alt="Preview Image #(HttpContext.Name)" width="100" height="100"
src="#(filesMCQ.Count > 0 ?
filesMCQ.Where(item => item.Name == HttpContext.Name)?.FirstOrDefault()?.Path : string.Empty
)">
</td>
<td>
<div style="padding: 7px; width: 50px;">
<h5 title="#(HttpContext.Name)">#(HttpContext.Name)</h5>
<i>#(HttpContext.Size) Bytes</i>
</div>
</td>
this code generate when in click on ADD line button. Here is the code of Addline
private async void AddLine()
{
cursor(true);
tMCQ item = new tMCQ();
MCQNumber++;
item.MCQDescription = mCQ.MCQDescription;
item.MCQ_Id = MCQNumber;
item.Code = char.ConvertFromUtf32(64 + MCQNumber);
MCQImage();
item.ImagePath = mCQ.ImagePath;
tblMCQ.Add(item);
CodeNumber++;
mCQ.MCQDescription = "";
Mcqfile = null;
filesMCQ = new List<fileInfos>
();
contentMCQ = null;
McqImagePath = null;
argsRemove = null;
}
MultipartFormDataContent code
public MultipartFormDataContent contentMCQ;
if (contentMCQ != null)
{
string FileName = Guid.NewGuid().ToString() + "." + filesMCQ.FirstOrDefault().Name.Split('.')[1].ToString();
using (var ms = new FileStream(item.ImagePath = new ExtensionMethods().SaveTo(FileName), FileMode.Create))
{
await contentMCQ.FirstOrDefault().CopyToAsync(ms);
}
}
Question Screen
Related
I am developing an application where I have to get the data from an Excel sheet and use it in the application, but I am having trouble accessing the data. Should I use Entity Framework and move the Data to a database or do I just import the data from Excel and use it?
Not sure what trouble you are meeting to access the data. But here is a sample about importing Excel data to Asp.net core application, you could refer to it.
In this sample, it will upload the excel file to the wwwroot folder using JavaScript first, then, using the DotNetCore.NPOI package (open source, you could install it via Nuget) to extract the data from excel. Details steps as below:
Suppose there have a testdata.xlsx file, the content as below:
Code in the controller:
private readonly IWebHostEnvironment _hostEnvironment;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment)
{
_logger = logger;
_hostEnvironment = environment;
}
public IActionResult Upload()
{
return View();
}
[HttpPost]
public IActionResult Import()
{
IFormFile file = Request.Form.Files[0];
string folderName = "UploadExcel";
string webRootPath = _hostEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
StringBuilder sb = new StringBuilder();
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
ISheet sheet;
string fullPath = Path.Combine(newPath, file.FileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
stream.Position = 0;
if (sFileExtension == ".xls")
{
HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
else
{
XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
IRow headerRow = sheet.GetRow(0); //Get Header Row
int cellCount = headerRow.LastCellNum;
sb.Append("<table class='table table-bordered'><tr>");
for (int j = 0; j < cellCount; j++)
{
NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
sb.Append("<th>" + cell.ToString() + "</th>");
}
sb.Append("</tr>");
sb.AppendLine("<tr>");
var emplist = new List<EmployeeViewModel>();
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
}
sb.AppendLine("</tr>");
EmployeeViewModel emp = new EmployeeViewModel() {
EmployeeID = Convert.ToInt32(row.Cells[0].ToString()),
EmployeeName = row.Cells[1].ToString(),
Age = Convert.ToInt32(row.Cells[2].ToString()),
Sex = row.Cells[3].ToString(),
Designation = row.Cells[4].ToString()
};
emplist.Add(emp);
}
var result = emplist;
sb.Append("</table>");
}
}
return this.Content(sb.ToString());
//return View("Upload");
}
Code in the Upload view:
<form asp-controller="Home" asp-action="Export">
<div class="container">
<div class="row">
<div class="col-md-4">
<input type="file" id="fileupload" name="files" class="form-control" />
</div>
<div class="col-md-3">
<input type="button" name="Upload" value="Upload" id="btnupload" class="btn btn-primary" />
Download
</div>
<div class="col-md-5">
<input type="submit" name="Export" value="Create and Export" id="btnExport"
class="btn btn-primary" asp-action="Export" />
</div>
</div>
<div class="clearfix"> </div>
<div class="row">
<div id="divPrint"></div>
</div>
</div>
</form>
And the Java Script code:
<script type="text/javascript">
$(function () {
$('#btnupload').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file.");
return false;
}
else {
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) == -1) {
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fileupload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax({
type: "POST",
url: "/Home/Import",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
$('#divPrint').html(response);
}
},
error: function (e) {
$('#divPrint').html(e.responseText);
}
});
})
$('#btnExport').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file then Import");
return false;
}
});
});
</script>
The result like this:
You could also create a Employee model to store the data:
public class EmployeeViewModel
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
public string Designation { get; set; }
}
Then, when loop through the excel rows, use the following code to get the Employee List:
var emplist = new List<EmployeeViewModel>();
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
}
sb.AppendLine("</tr>");
EmployeeViewModel emp = new EmployeeViewModel() {
EmployeeID = Convert.ToInt32(row.Cells[0].ToString()),
EmployeeName = row.Cells[1].ToString(),
Age = Convert.ToInt32(row.Cells[2].ToString()),
Sex = row.Cells[3].ToString(),
Designation = row.Cells[4].ToString()
};
emplist.Add(emp);
}
If the above sample doesn't achieve your requirement, please explain more details about what trouble are you having and what library you are using to upload the excel.
Reference:
Import and Export Excel file using NPOI
Import (Insert) Excel file data into Database ASP.Net Core MVC (using OLEDB library)
How can i get the selected row KendoGrid Data Item?
I research a lot online and I came across this post http://dojo.telerik.com/egUpI which does exactly what i am looking for i would like implement the same.
I have the following code to populate grid in asp.net view. I need your help when row selected populate a elements.
Here is my Grid View:
<h1> Contacts</h1>
#{
var gridColumnSettings = new List<GridColumnSettings>
{
new GridColumnSettings
{
Member = nameof(Contact.Name),
MemberType = typeof(string)
},
new GridColumnSettings
{
Member = nameof(Contact.PhoneNumber),
MemberType = typeof(string)
}
};
var gridViewModel = new GridViewModel
{
Name = "ContactGrid", // Grid Name
Columns = gridColumnSettings,
AutoBind = true,
DataSourceSettings = new GridDataSourceSettings
{
ReadDataSource = new DataSourceSetting()
{
ActionName = "Contact",
ControllerName = "Contact",
HttpVerb = HttpVerbs.Get,
}
},
SelectionSettings = new GridSelectionSettings
{
IsSelectable = true, // To make grid selectable
GridSelectionMode = 0,
GridSelectionType = 0
},
}
};
}
Here is my Form on the same Page to display the selected grid row information
<form>
<h3>Name</h3>
<div class="col-sm-3">
<input type="text" readonly class="form-control " id="Name">
</div>
<h3>Phone</h3>
<div class="col-sm-3">
<input type="text" readonly class="form-control" id="Phone">
</div>
</form>
I tried this Jquery, but not working
<script>
function fillForm() {
$("#ContactGrid").kendoGrid({
change: function (e) {
var dataItem = this.dataItem(this.select());
fillForm(dataItem);
}
});
}
// Fill Form based on the selected row
var fillForm = function(dataItem) {
var columns = $("#ContactGrid").data("kendoGrid").options.columns;
var form = $("form");
for (var i = 0; i < columns.length; i++) {
var field = columns[i].field;
form.find("#" + field).val(dataItem[field]);
}
}
</script>
i have a table for saving some ids for send request to web service and save my data to view model and show data in view page with IEnumerable viewmodel.Now i want to have a pagination at the end of my page because i have more than 100 product in my archive page.Now how can i have Pagination for this page??
//CONTROLLER
public ActionResult Archive()
{
var selectspecial = db.ProviderSelections.Where(a =>
a.SpecialSuggestion == true && a.IsActive ==
true).OrderByDescending(a => a.CreateDate).Select(a =>
a.ID).ToList();
var lastitem = selectspecial.Last();
List<string> lst = new List<string>();
for (int i = 0; i < selectspecial.Count; i++)
{
var selectid = selectspecial[i];
lst.Add(selectid.ToString());
}
StringBuilder itemlist = new StringBuilder();
foreach (var item in lst)
{
itemlist.Append(item).Append(",");
}
string id = itemlist.ToString() + lastitem;
WebClient webclient = new WebClient();
webclient.Headers[HttpRequestHeader.ContentType] =
"application/json;charset=utf-8";
string url = "MYWEBSERVICEURL?pids=" + id;
webclient.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.Default.GetBytes("USERNAME:PASSWORD"));
webclient.Headers.Add("Request-type", "REQUESTTYPE");
string result = webclient.DownloadString(url);
JObject jObject = JObject.Parse(result);
JToken jUser = jObject["X"];
List<BriefDetailsViewModel> briefdetails = new
List<BriefDetailsViewModel>();
foreach (var item in jUser)
{
BriefDetailsViewModel brief = new BriefDetailsViewModel();
brief.address = (string)item["address"];
//OTHER LINES ARE LIKE ABOVE LINE
briefdetails.Add(brief);
}
return View(briefdetails);
}
//Archive.cshtml
#model IEnumerable<ROOT.BriefDetailsViewModel>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
#foreach (var item in Model)
{
<div class="col-lg-9 col-md-9 col-sm-8 col-xs-8">
<div class="text TextBox">
#item.description
</div>
</div>
//More Data like this....
}
//PAGINATION BOX
</div>
The best practice by adding pagination feature to your web service to be like this :
string url = "MYWEBSERVICEURL?pids=" + id + "&pageId="+pageId;
Also use page size variable, then you can page your data using LINQ :
example :
int numberOfObjectsPerPage = 10;
var queryResultPage = dataContext.Employees.OrderBy(a=>a.ID)
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(numberOfObjectsPerPage).ToList();
If you cannot update your web service, or you are using external web service you can read the data then page it before return your view :
briefdetails = briefdetails
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(numberOfObjectsPerPage);
return View(briefdetails);
Also in your html you can render something for paging below your table :
//You called it PAGINATION BOX
for(int i=1,i<pageNumber;i++)
{
<a href="#Url.Action("YOUR_ACTION",new {pageId = i})">#i<a/>
}
I'm newbie in this field.
I have a table called comment. And i want to get multiple column data and multiple rows. Like I row-1 has two columns.
Can I use Linked List to pass data from controller to view?If so how should I do that. If not than how should I pass data from controller to view. I know ViewBag, Session etc. But they are no help to me.
When I run this code it gives me following exception
"Object reference not set to an instance of an object".
How should I code in controller and view too. Will there be a connection of this with model too?
Please if you have some source link about How to use LinkList in MVC4 Asp.Net, please do share.
Any kind of help will be much appreciated.
Controller
***>
Comment CommentObj = new Comment();
try
{
var query = from comment in db.Comments
from TeachOb in db.TeacherAccounts
from StdOb in db.StudentAccounts
select new
{
CommentBy = comment.UserID,
CommentOn = comment.PostID,
CommentContent = comment.CommentContent,
TeacherName = TeachOb.TeacherName,
StudentName = StdOb.UserName
};
LinkedList<string> getData = new LinkedList<string>();
LinkedListNode<string> Node = new LinkedListNode<string>("");
foreach (var Info in query)
{
if (Info.CommentOn == PostID && Info.CommentBy == Loggedinuser)
{
string commentBy = Info.CommentBy.ToString();
string commentOn = Info.CommentOn.ToString();
string commentContent = Info.CommentContent.ToString();
string teacherName = Info.TeacherName.ToString();
Node.Value = commentBy;
Node.Value = commentOn;
getData.AddFirst(Node);
}
Session["list"] = getData;
}
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
Blockquote
This my View
Blockquote
#foreach (var std in Session["list"] as LinkedList<string>)
{
<li>
<a href="#">
#std.ToString();
</a>
<br /><br />
</li>
}
Try with this may be this will help.
foreach (var Info in query)
{
if (Info.CommentOn == PostID && Info.CommentBy == Loggedinuser)
{
string commentBy = Info.CommentBy.ToString();
string commentOn = Info.CommentOn.ToString();
string commentContent = Info.CommentContent.ToString();
string teacherName = Info.TeacherName.ToString();
Node.Value = commentBy;
Node.Value = commentOn;
getData.AddFirst(Node);
}
}
if(getData!= null)
{
ViewBag.ListData = getData;
}
View Blog
#foreach (var std in ViewBag.ListData)
{
<li>
<a href="#">
#std.ToString();
</a>
<br /><br />
</li>
}
I written a view that display a table listing of thumbnails. It is working now. Next I am writing another view, which display a new view with detailed information of the
item thumbnail which was clicked. Right now, I am not sure how to add the information which makes the thumbmail clickable that routes to the GetDetailInfo Controller method
that return a detailed information view.
Here is my thumbnail table list code:
<table class="table-responsive" width="100%">
<tbody>
#foreach (var productGroup in Model.Select((e, i) => new { Product = e, Grouping = (i / 4) }).GroupBy(e => e.Grouping))
{
<tr>
#foreach (var product in productGroup)
{
<td>
<div><br /></div>
<img src=#product.Product.Thumbnail style="width: 100px; height: 100px" />
<div><br /></div>
</td>
}
</tr>
}
</tbody>
</table>
Here is my the Controller method which I am writing which is called when the thumbnail is click and return a detailed view.
[MvcSiteMapNode(Title = "Item Detail", ParentKey = "Item-Home", Key = "Item-Detail", PreservedRouteParameters = "itemId")]
[Route("~/item/{itemId}/detail")]
public async Task<ActionResult> GetDetailInfo(int itemId)
{
var result = await ItemService.GetDetailInfo(contentId) );
return View(result.Dto);
}
I am not sure how to route the click on thumnbnail to this controller method to return a new detail info view. Any help is appreciated. Thanks
There are two common ways to make an image as a link.
1 - Using a link tag.
<a href="#Url.Action("GetDetailInfo", "Controller", new { itemId = product.Product.Id })">
<img src="#product.Product.Thumbnail" style="width: 100px; height: 100px" />
</a>
2 - Using a custom Html Helper
Source:
public MvcHtmlString ActionImage(this HtmlHelper htmlHelper,
string controller,
string action,
object routeValues,
string imagePath,
string alternateText = "",
object htmlAttributes = null)
{
var anchorBuilder = new TagBuilder("a");
var url = new UrlHelper(HtmlHelper.ViewContext.RequestContext);
anchorBuilder.MergeAttribute("href",url.Action(action,controller,routeValues));
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alternateText);
var attributes = (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
imgBuilder.MergeAttributes(attributes);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
anchorBuilder.InnerHtml = imgHtml;
return MvcHtmlString.Create(anchorBuilder.ToString());
}
Using:
#Html.ActionImage("Controller", "GetDetailInfo", new { itemId = #product.Product.Id }, "#product.Product.Thumbnail", "alternateText")
Asp.Net MVC Html Helper to create link with an image
The first method is handy - and rightly commented by Bardicer in your question, - but the second one is more practical.