Helper does not work (ASP.NET MVC ) - c#

I try to create a helper in my project.
This is my code:
#using VrBlog.Models;
#helper Render(Post post, System.Web.Mvc.HtmlHelper html, bool isAdmin, bool showComments)
{
<div class="postTitle">#post.Title</div>
<div class="postContainer">
<div class="postTabs">
<div class="dateTab">
<div class="month">#post.DateTime.Value.ToString("MMM").ToUpper()</div>
<div class="day">#post.DateTime.Value.ToString("dd")</div>
</div>
<div class="commentsTab">
#post.Comments.Count
</div>
</div>
<div class="postContent">
<div class ="postBody">#html.Raw(post.Body)</div>
<div class="tagList">
#foreach (Tag tag in post.Tags)
{
<span class="tag">#tag.Name</span>
}
</div>
<div class="linkList">
#{ string url = "http://www.mattblagden.com/posts/details/" + post.Id;}
</div>
</div>
</div>
if (showComments)
{
<div id="commentsContainer">
<a id ="comments"></a>
#foreach (Comment comment in post.Comments.OrderBy(x => x.DateTime))
{
<div class="comment">
<div class="commentName">
#if (!string.IsNullOrWhiteSpace(comment.Email))
{
#comment.Name
}
else
{
#comment.Name;
}
</div>
said:
<div class="commentBody">#html.Raw(html.Encode(comment.Body).Replace("\n", "<br/>"))</div>
<div class="commentTime">at #comment.DateTime.Value.ToString("HH:mm") on #comment.DateTime.Value.ToString("yyyy/MM/dd")</div>
</div>
}
<div id="commentEditor">
<div id="commentPromt">Leave a comment!</div>
<form action="#Href("~/Views/Posts/Comment/" + post.Id)" method="post">
<input type="text" id="commentNamePromt" name="name"/>Name (required)<br/>
<input type="text" id="commentEmailPromt" name="email" />Email (optional)<br/>
<textarea id="commentBodyInput" name="body" rows="10" cols="60"></textarea><br/>
<input type="submit" id="commentSubmitInput" name="submit" value="Submit!"/>
</form>
</div>
</div>
}
}
And after this, I try to call it from the view. My helper is in the AppCode folder inside the project.
I try to call it like this
#foreach (Post post in Model)
{
#PostHelper.Render(post,Html,isAdmin, false)
}
But I get the following error:
Error CS0103 The name 'PostHelper' does not exist in the current context
How I can fix this and why it not visible?

If you are calling the helper on the same page, try following:
#foreach (Post post in Model)
{
#Render(post, Html, isAdmin, false)
}

Change this
#foreach (Post post in Model)
{
#PostHelper.Render(post,Html,isAdmin, false)
}
to
#foreach (Post post in Model)
{
#Render(post,Html,isAdmin, false)
}

Rename your folder in App_Code
"We can define the #helper method outside of our view template, and enable it to be re-used across all of the view templates in our project.
We can accomplish this by saving our #helper methods within .cshtml/.vbhtml files that are placed within a \App_Code directory that you create at the root of a project."

Related

Value cannot be null. Arg_ParamName_Name

I am developing a project in asp.net mvc structure.I want to create the detail page of the books I bought from a web service, but I encountered a problem and could not solve it. I need help.
Web Api: https://gutendex.com/
These are the codes for my homepage.
#model BookListModel
<div class="col-md-12">
<div class="row">
#foreach (var books in Model.results)
{
<div class="col-md-3 text-truncate">
<img src="#books.formats.imagejpeg" alt="...">
<div class="card-body">
<h5 class="card-title">#books.title</h5>
</div>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<a class="btn btn-primary stretched-link" asp-controller="Book" asp-action="Details" asp-route-id="#books.id">Details</a>
<button type="button" class="btn btn-sm btn-outline-secondary">Add</button>
</div>
</div>
<br />
</div>
}
</div>
</div>
public class BookRepository
{
private static List<Result> results;
public static Result GetBooksById(int id)
{
return results.FirstOrDefault(b => b.id == id); // PROBLEM HERE
}
}
public IActionResult Details(int id)
{
return View(BookRepository.GetBooksById(id));
}
#model Result
<div class="card mb-3">
<div class="card-body">
<div class="row no-gutters">
<div class="col-md-3">
<img src="#Model.formats.imagejpeg" class="card-img">
</div>
<div class="col-md-9">
<h5 class="card-title">#Model.title</h5>
<p class="card-text">#Model.subjects</p>
<p class="card-text">
<small class="text-muted">3 days ago</small>
</p>
</div>
</div>
</div>
</div>
I wrote a book repository class to help me, the id of the book comes from there with the help of a button, but my method returns a null value.
It gives an error here, it returns null.
Your private static List<Result> results; is null. You should initialized that at some point/somewhere. Or load data into it, whatever is your intent. At least that is what the errors indicates, FirstOrDefault is an extensions method called on the collection, but that fails if said collection is null. And your code does not show if it is initialized somewhere.
i.e.
results = new List<Result> { new Result(...) }

Problem with saving value with the input type number to the chosen field to the database by C# in ASP .NET MVC

I have a problem with implement saving value with input type number to the database. I have created website with ASP .NET MVC with UnitOfWork and Repositories. I have a Commodity model, where I have field Amount, and I have HomeViewModel in which I have a field Amount also. I would like to overwrite the amount field from the commodity model. Should I use onchange or onclick in input or a tags in html code, or all with my basic ideas are nonsens ?
Below is the code snippet with view created in RazorPages with extension .cshtml.
<div class="col-12">
<div class="row my-3">
#foreach(var Commodity in Model.CommodityList.Where(c=>c.CategoryId==category.Id))
{
<div class="col-lg-4 col-xl-3 col-md-6 pb-4">
<div class="card" style="border:2px solid #43ac6a;border-radius:5px;
backgroundcolor: #fffeee">
<div class="pl-3 pt-1 text-center">
<h3 class="card-title text-primary"><b>#Commodity.Name</b></h3>
</div>
<div class="d-flex justify-content-between">
<div class="pl-1 text-muted">#localizer.Get("Price")</div>
<div class="pr-1 text-danger h5">$#Commodity.Price</div>
</div>
<img src="#Commodity.ImageUrl" class="card-img-top p-2 rounded" />
<div class="col-9">
<input onchange="save()" asp-for="#Commodity.Amount" type="number"
id="quantity" name="quantity" min="0" max="100" />
</div>
<a onclick="save()" asp-action="Details" class="btn btn-success"
style="border-
radius:2px;" asp-route-id="#Commodity.Id"
onclick="save()">#localizer.Get("Details")</a>
</div>
</div>
}
</div>
</div>
My problem is that I can't write the value from after pressing the button below as the tag.
Below is the method written by me in controller regarding to the view
public IActionResult Index()
{
HomeVM = new HomeViewModel()
{
CategoryList = _unitOfWork.Category.GetAll(),
CommodityList = _unitOfWork.Commodity.GetAll(includeProperties: "Category"),
ServiceList = _unitOfWork.Service.GetAll(includeProperties: "Category,Payment"),
EmployeeList = _unitOfWork.Employee.GetAll(includeProperties: "Service"),
Amount = _unitOfWork.Commodity.GetFirstOrDefault(includeProperties:
"Category").Amount
};
foreach (var commodity in (_unitOfWork.Commodity.GetAll(includeProperties:
"Category")))
{
var CommodityFromDb = commodity;
CommodityFromDb.Amount = HomeVM.Amount;
_unitOfWork.Save();
}
_unitOfWork.Save();
return View(HomeVM);
}
I have a guess that you probably need to do it somehow with jquery, in a file with the extension js, but I have no idea how. I would be grateful for any help.

Replace a PartialView with another one (ASP NET CORE MVC)

I'm using ASP NET CORE MVC 5.
I have a View ("ChooseServices") which, depending on the parameter passed, displays 1 or N PartialViews (Forms):
ChooseServices.cshtml:
<div class="col">
#if (Model.OfferServiceA)
{
<partial name="_FormA" />
}
#if (Model.OfferServiceB)
{
<partial name="_FormB" />
}
#if (Model.OfferServiceC)
{
<partial name="_FormC" />
}
</div>
After answering each Form individually, I want to display a default message which is another PartialView ("_confirmation.cshtml") in place of the Form.
Something like this:
(after submit Form-A)
(and after submit Form-C)
In summary, after submitting a Form (partial view), I want it be replaced by another PartialViews, all inside the View "ChooseServices".
[EDIT - Some code]
CONTROLLER:
public class SomeServiceController : Controller
{
// A survey brings to here.
public IActionResult ChooseServices(SuggestedServicesDTO dto)
{
return View(dto);
}
}
VIEWS (ignoring css)
ChooseServices.cshtml
#model SuggestedServicesDTO
<section >
<div class="container">
<div class="row">
<div class="col">
#if (Model.OfferServiceA)
{
<partial name="_FormA" />
}
#if (Model.OfferServiceB)
{
<partial name="_FormB" />
}
#if (Model.OfferServiceC)
{
<partial name="_FormC" />
}
</div>
</div>
</div>
</section>
_Form{x}.cshtml
{x} is the service name.
<div class="card">
<div class="card-body">
<h3>THIS IS THE FORM-{x}.</h3>
<form asp-action="??IDK what put here">
<div>
<label>Select an option:</label>
<!-- Radio buttons Begin -->
<div>
<label for="service{x}Opt{N}">
<input type="radio" name="optionsService{x}" id="service{x}Opt{N}" value="someValue1">
<span>Option QWERTY</span>
</label>
</div>
<div>
<label for="service{x}Opt{N}">
<input type="radio" name="optionsService{x}" id="service{x}Opt{N}" value="someValue2">
<span>Option ASDFGH</span>
</label>
</div>
<!-- others options here -->
<!-- Radio buttons end-->
</div>
<div>
<input type="submit" value="Submit {x}"/>
</div>
</form>
</div>
</div>
_Confirmation.cshtml
(Just a message, nothing important)
<div class="card">
<div class="card-body">
<div>
<h3>Thanks for answering!</h3>
<p>bla bla bla bla</p>
<button type="button" onclick="window.open('someurl', '_blank').focus();">
Do something...
</button>
</div>
</div>
</div>
I don't know what to do after submit de Forms{x}.

Dropzone FileUpload

Dear friends I am currently creating an admin panel for user where they can easily can publish their articles. I also want to add to my form a little fileuploader but sadly I got some problems with DROPZONEJS.JS file in POST method. The main problem is I cannot give URL to project's local file in order to download to file there where website will access those file in order to publish them with current article's id. Please let me know if there is something not understandable.
#{
ViewBag.Title = "Uppy";
}
#{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<div class="content d-flex flex-column flex-column-fluid" id="kt_content">
<!--begin::Entry-->
<div class="d-flex flex-column-fluid">
<!--begin::Container-->
<div class="container">
<!--begin::Card-->
<div class="card card-custom gutter-b">
<div class="card-header">
<div class="card-title">
<h3 class="card-label">File Upload</h3>
</div>
</div>
<!--begin::Form-->
<form>
<div class="card-body">
<div class="form-group row">
<label class="col-form-label col-lg-3 col-sm-12 text-lg-right">Multiple File Upload</label>
<div class="col-lg-4 col-md-9 col-sm-12">
<div class="dropzone dropzone-default dropzone-primary" id="kt_dropzone_2">
<div class="dropzone-msg dz-message needsclick">
<h3 class="dropzone-msg-title">Drop files here or click to upload.</h3>
<span class="dropzone-msg-desc">Upload up to 10 files</span>
</div>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-lg-3 col-sm-12 text-lg-right">File Type Validation</label>
<div class="col-lg-4 col-md-9 col-sm-12">
<div class="dropzone dropzone-default dropzone-success" id="kt_dropzone_3">
<div class="dropzone-msg dz-message needsclick">
<h3 class="dropzone-msg-title">Drop files here or click to upload.</h3>
<span class="dropzone-msg-desc">Only image, pdf and psd files are allowed for upload</span>
</div>
</div>
</div>
</div>
</div>
#using (Html.BeginForm("Uppy",
"FileUpload",
FormMethod.Post,
new { enctype = "multipart/form-data" })) //multipart/form-data gives functionlity to inputes (search at web);
{
<div class="card-footer">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-4">
<input type="submit" value="Submit" class="btn btn-light-primary mr-2" />
<button type="reset" class="btn btn-primary">Cancel</button>
</div>
</div>
</div>
}
</form>
<!--end::Form-->
</div>
<!--end::Card-->
<!--end::Row-->
</div>
<!--end::Container-->
</div>
<!--end::Entry-->
</div>
<!--end::Content-->
By the way my own upload code is working correctly and also sends choosen file to url location where I wrote in controller.
<label for="file">Upload File:</label>
<input type="file" name="file" id="file" class="btn-hover-bg-success" />
<br>
<br>
<input type="submit" value="Upload Image" />
<br>
<br>
#ViewBag.Message
This is my FileUploadController:
[HttpPost]
public ActionResult Uppy(HttpPostedFileBase file)
{
ADAPTIVE_TESTEntities ent = new ADAPTIVE_TESTEntities();
Adaptive.News.Models.NEWS news = new Adaptive.News.Models.NEWS();
if (file != null && file.ContentLength > 0)
try
{
var path = Path.Combine(Server.MapPath("~/Content/images"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
news.PICTUREPATH = path;
ent.NEWS.Add(news);
ent.SaveChanges();
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR: " + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
return View();
}
it is not obvious to me, what and where really your problem is. What do you mean with having problem. Is your problem with Dropzone.JS or with C#? Anyway, I examined your code slightly and have some ideas what your problem could be.
FIRST OF ALL: You have 2 DIV containers, which you use as Dropzone elements assigning them the css class "dropzone". Furthermore you generate a FORM element with ASP.Net HTML-Helper.
By default you have 2 options using Dropzone.
Declarative instantiation via assigning css class "dropzone" to any HTML element.
Dropzone discovers all DOM elements with class="dropzone" automatically and instantiates them.
Programmatically instantiating: You instantiate Dropzone by passing the id of the container element and THE OPTIONS CONTAINING POST URL to the Dropzone constructor.
DECLARATIVE DROPZONE
You must pay attention to this detail: If you use FORM element as Dropzone container element, Dropzone uses "action" attribute of the FORM element as post URL. But if you use
DIV element as container, then you get most possibly a JavaScript error. Because DIV elements do usually NOT have "action" attribute. If you use DIV as Dropzone container (and in your code you use it 2 times), you will get following JavaScript error:
dropzone.js:1027 Uncaught Error: No URL provided.
at new Dropzone (dropzone.js:1027)
at dropzone.js:2907
at Function.Dropzone.discover (dropzone.js:2919)
at Dropzone._autoDiscoverFunction (dropzone.js:3491)
at HTMLDocument.init (dropzone.js:3456)
In this case you have two options solve the problem:
Use FORM element instead of DIV as Dropzone container.
Add action="/your/post/url" to your DIV element, which you use as Dropzone container.
Where I would prefer the first option. Because it is not common that DIV elements have action attribute.

How to reuse HTML snippets in asp.net core razor page?

I try to reuse HTML snippets in my razor page (view component) but somehow it never call or hit the break in the html section.
I'm using Asp.net core 2.2
#{
Func<CategorySimpleModel, Microsoft.AspNetCore.Html.IHtmlContent> DisplayManufacturerPicture=
#<div class="col-sm-4">
<div class="row">
#foreach (var m in item.Manufacturers)
{
<div class="col-md-6 col-sm-12">
blah blah
</div>
}
</div>
</div>;
}
#foreach (var root in Model.Categories)
{
DisplayManufacturerPicture (root);
}
somehow it only works with # though the method call is inside the server side syntax
#if (root.Manufacturers.Count > 0)
{
#DisplayManufacturerPicture(root);
}
What you are trying to do is not (yet) possible. You should take a look at partial views instead:
#foreach (var root in Model.Categories)
{
<partial name="_DisplayManufacturerPicture" model="root" />
}
And then inside _DisplayManufacturerPicture.cshtml:
#model CategorySimpleModel
<div class="col-sm-4">
<div class="row">
#foreach (var m in item.Manufacturers)
{
<div class="col-md-6 col-sm-12">
blah blah
</div>
}
</div>
</div>

Categories

Resources