Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

How To Access A Custom Class Function In a View

$
0
0

How do access a custom class function from a view, it is a static class


Authorization inside controller

$
0
0

Hey, I want to create system were if user is Admin then on page are shown every row from database, otherwise only related to current user. I need sth like this 

if ((await AuthorizationService.AuthorizeAsync(User, "UserIsAdmin")).Succeeded)
{
select * from database and show
}else{

select * from database where UserId = currentUser

}

but Authorizationservice.Authorize async can only be used in async method. Can I do sth similiar with sync method?

JavaScript critical error in http://localhost:2825/js/comboTreePlugin.js\n\nSCRIPT1002: Syntax error

$
0
0

Please can you help me how to fix  the error while running IE . The error message is being showed 

'JavaScript critical error at line 450, column 40 in http://localhost:2825/js/comboTreePlugin.js\n\nSCRIPT1002: Syntax error'. The error is coming in the code given below starting with .filter((index, item) =>. 

Please can you help me  how to fix it

 ComboTree.prototype.filterDropDownMenu = function () {
        var searchText =  '';
        if (!this.options.isMultiple)
            searchText = this._elemInput.val();
        else
            searchText = $("#" + this.comboTreeId + "MultiFilter").val();

        if (searchText != ""){
            this._elemItemsTitle.hide();
            this._elemItemsTitle.siblings("span.comboTreeParentPlus").hide();
            list = this._elemItems .filter((index, item) => {
                    return item.innerHTML.toLowerCase().indexOf(searchText.toLowerCase()) != -1;
                })
                .each(function (i, elem) {$(this.children).show()$(this).siblings("span.comboTreeParentPlus").show();
                });
        }
        else{
            this._elemItemsTitle.show();
            this._elemItemsTitle.siblings("span.comboTreeParentPlus").show();
        }
    }

.Net Core 3.0 MVC app | Unable to receive response to the client from APIController

$
0
0

Appreciate if you can help me with this issues, it could be minot but am unable to crack it.

Problem,

Although API is being called but there is NO response coming back to the browser. Status is showing as cancelled in network tab under chrome devtools, any idea what's happing here? I am unable to crack this out

My code details -

In my _layout file I am using following CDN scripts at the last just before today tag closing and Jquery CDN in html tag,

<scriptsrc="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"crossorigin="anonymous"async></script><scriptsrc="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"crossorigin="anonymous"async></script>

 have a API controller, listed as below

I have a api controller, listed as below

And this is how am calling above api through Jquery from one of the View

And Startup.cs look like below,

How to Server Side Rendering with ASP.NET Core and React.js (No MVC) ?

$
0
0

Hello,

I'm developing an application with ASP.NET Core and React.js, my project was created with Visual Studio 2019, ( I have selected React.js project on Visual Studio 2019's list ).

Now i need to do the SEO and Adding a few Tags OG to my project, i know that need to be done at the server SSR (Server Side Rendering), i have followed many tutorial, but all they use the MVC project which have theView Folder  and .cshtml files, and actualy i don't have this on my project.

I have no idea how make the server pre-render the HTML file in this case !

Unfortunately this thread was Angular :(

i will be grateful for your help !

Resource based authorization, passing every parameters to authorization handler

$
0
0

I'm new to resource based authorization. I did it with help of link. I want to allow editing licence only by admin or user who created it. I wonder if it is ok to pass to authorization handler not only licence user id but also current user id and IsAdmin bool and check it inside handler.

public async Task<IActionResult> OnGetAsync()
{

var authorize = new AuthorizationAuthor { CurrentUserId = currentUserId, 
LicenceUserId= licenceUserId,
IsAdmin = ((ClaimsIdentity)User.Identity).HasClaim("IsAdmin", "true") };

var authorizationResult = await authorizationService.AuthorizeAsync(User, authorize, "EditLicencje");

if (authorizationResult.Succeeded)
{

//do sth

}

}

services.AddAuthorization(options =>
            {
                options.AddPolicy("EditLicencje", policy =>
                    policy.Requirements.Add(new SameAuthorRequirement()));
            });
            services.AddSingleton<IAuthorizationHandler, LicenceAuthorizationHandler>();

    public class AuthorizationAuthor
    {
        public string LicenceUserId { get; set; }
        public string CurrentUserId { get; set; }
        public bool IsAdmin { get; set; }
    }

public class LicenceAuthorizationHandler : AuthorizationHandler<SameAuthorRequirement, AuthorizationAuthor>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       SameAuthorRequirement requirement,
                                                       AuthorizationAuthor resource)
        {
            if (resource.CurrentUserId == resource.LicencjaUserId || resource.IsAdmin)
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }

    public class SameAuthorRequirement : IAuthorizationRequirement { }






Problems in implementing Asynchronous Action: The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IAsyncQueryProvider can be used for Entity Framework asynchronous operations

$
0
0

Hi out there:

I got a problem in implementing an Asynchronous Action. Here is my code bit by bit.

1) The  Repository interface 

public interface IGenericRepository<T> where T : class
{

IQueryable<T> GetAllIncluding(Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeProperties = "");

}

2) The Generic Repository 

public class GenericRepository<T> : IRepository<T> where T : class
{
private readonly HousingContext _DbContext;

private readonly DbSet<T> dbSet;

public GenericRepository(HousingContext context)
{
this._DbContext = context;
this.dbSet = this._DbContext.Set<T>();
}

public virtual IQueryable<T> GetAllIncluding(Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeProperties = "")
{

IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}

foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}

if (orderBy != null)
{
return orderBy(query);
}
else
{
return query;
}
}

To avoid irreverent code, I omitted the unit of works  and the view model class as they work with a synchronous action. So I go straight to the controller action which is the one that triggers the exception.

3) controller 

public async Task<IActionResult> Index(string sortField, string currentSortField, string currentSortOrder, string SearchString, int? pageNo, string currentFilter)
{


List<InvoiceViewModel> viewmodel = new List<InvoiceViewModel>();
//eager loading
var Invoice_List = (from i in this._UoW.InvoicesRepository.GetAllIncluding(includeProperties: "FinancialyearNavigation,IdContractAmountsNavigation.IdContractNavigation.IdCompanyNavigation,IdContractAmountsNavigation.IdContractNavigation.ProjectNavigation")
select new
{
i.Id,
i.FinancialyearNavigation.Financialyear1,
i.IdContractAmountsNavigation.IdContractNavigation.IdCompanyNavigation.Companyname,
i.Financialyear,
i.IdContractAmountsNavigation.ScopeOfWorks,
i.IdContractAmountsNavigation.IdContract,
i.IdContractAmountsNavigation.IdContractNavigation.ProjectNavigation.Project,
IdProject = i.IdContractAmountsNavigation.IdContractNavigation.ProjectNavigation.Id,
i.Invoicenumber,
i.Workdone,
i.SubmissionDate,
i.ApprovedDate


});
foreach (var item in Invoice_List)
{
InvoiceViewModel objcvm = new InvoiceViewModel();

objcvm.Id = item.Id;
objcvm.Invoice = item.Invoicenumber;
objcvm.Id_Contract = (int)item.IdContract;
objcvm.Financial_year = item.Financialyear1;
objcvm.Id_Financialyear = (int)item.Financialyear;
objcvm.Company = item.Companyname;
objcvm.Project = item.Project;
objcvm.scopeofworks = item.ScopeOfWorks;

objcvm.SubmissionDate = item.SubmissionDate;
objcvm.ApprovedDate = item.ApprovedDate;
objcvm.WorkDone = (decimal)item.Workdone;
objcvm.Id_Project = (int)item.IdProject;
viewmodel.Add(objcvm);

}
if (SearchString != null)
{
pageNo = 1;
}
else
{
SearchString = currentFilter;
}
ViewData["Invoice"] = sortField;
ViewBag.CurrentFilter = SearchString;

if (!String.IsNullOrEmpty(SearchString))
{
viewmodel = viewmodel.Where(s => s.Invoice.Contains(SearchString)).ToList();


}
viewmodel = this.SortViewModelData(viewmodel, sortField, currentSortField, currentSortOrder);

int pageSize = 10;


return View(await PagingList<InvoiceViewModel>.CreateAsync(viewmodel.AsQueryable<InvoiceViewModel>().AsNoTracking(), pageNo ?? 1, pageSize));

}

The debugger says:

InvalidOperationException: The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IAsyncQueryProvider can be used for Entity Framework asynchronous operations.

<div class="titleerror">
  • Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync<TSource, TResult>(MethodInfo operatorMethodInfo, IQueryable<TSource> source, Expression expression, CancellationToken cancellationToken)

  • Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync<TSource, TResult>(MethodInfo operatorMethodInfo, IQueryable<TSource> source, CancellationToken cancellationToken)

  • Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.CountAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)

  • Finance_Management.Paging.PagingList<T>.CreateAsync(IQueryable<T> source, int pageIndex, int pageSize) in PagingList.cs

    <button class="expandCollapseButton" data-frameid="frame4">+</button> <div class="source">
    1. var count = await source.CountAsync();
    </div>
  • Finance_Management.Controllers.InvoicesController.Index(string sortField, string currentSortField, string currentSortOrder, string SearchString, Nullable<int> pageNo, string currentFilter) in InvoicesController.cs

    <button class="expandCollapseButton" data-frameid="frame5">+</button> <div class="source">
    1. return View(await PagingList<InvoiceViewModel>.CreateAsync(viewmodel.AsQueryable<InvoiceViewModel>().AsNoTracking(), pageNo ?? 1, pageSize));
    </div>
  • Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)

  • System.Threading.Tasks.ValueTask<TResult>.get_Result()

  • System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult()

</div>

4)  PagingListClass 

public class PagingList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }

public PagingList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);

this.AddRange(items);
}

public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}

public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}

public int TotalPageNo
{
get
{
return TotalPages;
}
}


public static async Task <PagingList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PagingList<T>(items, count, pageIndex, pageSize);
}


}
}

Your assistance is much appreciated. 

How and where do you post "Jquery Ajax post" in Razor pages

$
0
0

hi guys

I am new to razor pages, but have a wealth of experience in other .net apps

I am working on a personal project that heavily requires JQuery posts e.g. seen below. My question is, where do I post the requests to ? Do I create a controller and post to the controller ? If so, then do I get the scaffolding controller actions to create the CRUD pages, which the controller will serve back ?  Or do I post to another razor page ?

Please help

I have been searching online for examples, but I only see MVC examples

        function LearningRazor(input) {

            var token = $('#__RequestVerificationToken').val();$.ajax({

                type: "POST",
                url: "/Upload/AjaxUpload",
                contentType: false,
                processData: false,
                data: formData,
                success: function (message) {
                  /// test
                },
                error: function (message) {
                   /// test
                }

            });
        };



Unable to cast object of type 'System.String' to type 'System.Int32'. Please help urgent

$
0
0

I deleted from the sqlserver table an unnecessary constraint from the user table. After that  the error being always showed  Unable to cast object of type 'System.String' to type 'System.Int32'. in general Repo. Please help urgent in the line . How can I fix Please help

 public T Get(int id)
        {
            return dbSet.Find(id);
        }

Compatibility Issues With SignalR and NetCore 3.1

$
0
0

I am following this tutorial to create a real-time progress bar.  This article I am following is 4 years old, and I am using a different version of Net Core.  I am using the current version, which is ASP Net Core 3.1. 

I believe the errors I am getting stem from the fact that I am using version 3.1 of Net Core.  This is the article I which I am using:

https://www.codeproject.com/Articles/1124691/SignalR-Progress-Bar-Simple-Example-Sending-Live-D

Everything seems to be running fine until I reach this part.

        public static void SendProgress(string progressMessage, double progressCount)
        {
            //IN ORDER TO INVOKE SIGNALR FUNCTIONALITY DIRECTLY FROM SERVER SIDE WE MUST USE THIS
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();

            //CALCULATING PERCENTAGE BASED ON THE PARAMETERS SENT
            // var percentage = (progressCount * 100) / totalItems;
            var percentage = (progressCount);

            //PUSHING DATA TO ALL CLIENTS
            hubContext.Clients.All.AddProgress(progressMessage, percentage + "%");
        }

    }
}

The first issue is that I am getting "GlobalHost does not exist in the current context for this line of code":

var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();

The second issue is that that I am getting "

<div>Severity Code Description Project File Line Suppression State</div> <div>Error CS0119 'HubClientsExtensions.Clients<T>(IHubClients<T>, string)' is a method, which is not valid in the given context" for this line of code:

 hubContext.Clients.All.AddProgress(progressMessage, percentage + "%");

Any suggestions would be kindly appreciated.

Set a value in a view model if user clicks a button and hide an element

$
0
0

i would appreciate some help figuring out how to set a value in a model via javascript from the view,

I want to set isDeleted property to true if the user clicks on the button of delete in one of SentencesLists[], then hide that row from the table and deal with the sentence in the action.

i would like to set the proberty in the model it self via javascript so when i get the model result in action i get the sentences that are clicked to delete.

Any recomendations?

EditStoryViewModel

    public class EditStoryViewModel
    {
        public IEnumerable<Childs> ChildrenList { get; set; }
        public Childs Child { get; set; }
        public Story Story { get; set; }
        public IList<SentenceViewModel> SentencesLists { get; set; }

    }

SentenceViewModel

    public class SentenceViewModel
    {
            public int Id { get; set; }
            public string SentenceText { get; set; }
            public string SequenceNo { get; set; }
            public bool isDeleted { get; set; } // WHAT I NEED TO SET TO TRUE IF USER CLICKS VIA JAVASCRIPT
            public Image Image { get; set; }
            public IFormFile ImageFile { get; set; }
            public IFormFile AudioFile { get; set; }
    }

My View

@model TestApplication.Models.ViewModels.EditStoryViewModel
................................ Lines of code ...................................<tbody id="heree">
                                            @for (int i = 0; i < Model.SentencesLists.Count; i++)
                                            {<partial name="_SentenceEditor" for="@Model.SentencesLists[i]" />
                                            }</tbody><tfoot><tr><td colspan="5" style="text-align: left;"><a id="addItem" asp-action="BlankSentence" asp-controller="Story" class="btn btn-primary btn-lg btn-block ">Add Sentence</a> <br /></td></tr></tfoot>
................................ Lines of code ...................................
@section Scripts
{<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script><script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script><script type="text/javascript">$("#addItem").click(function () {$.ajax({
                url: this.href,
                cache: false,
                success: function (html) { $("#heree").append(html); }
            });
            return false;
        });</script>

}

PartialView

@model TestApplication.Models.ViewModels.SentenceViewModel
@using HtmlHelpers.BeginCollectionItemCore;
@{
    ViewData["Title"] = "_SentenceEditor";
}<tr id="editorRow">
    @using (Html.BeginCollectionItem("SentencesLists"))
    {<td class="col-md-4"><input asp-for="@Model.SentenceText" type="text" class="form-control"></td><td class="text-center col-md-2">
            @if (Model.Image != null)
            {<img src="@Model.Image.ImageSelected" /> <input asp-for="@Model.Image.ImageSelected" type="text" hidden />}
            else
            {<h6>-</h6>}</td><td class="col-md-2"><input asp-for="@Model.ImageFile" type="file" class="form-control-file border"></td><td class="col-md-2"><input asp-for="@Model.AudioFile" type="file" class="form-control-file border" disabled></td><td class="col-md-1"><input type="submit"  asp-controller="Story" asp-action="DeleteSentence" asp-route-id="@Model.Id" class="btn btn-md btn-danger ibtnDel" id="deleteRow" value="Delete" /></td><td class="col-md-1"><input asp-for="@Model.Id" type="text" class="form-control" hidden></td>
    }</tr>


@section Scripts {

    <script type="text/javascript"></script>
}

Action

        [HttpPost]
        public async Task<IActionResult> Edit(EditStoryViewModel model)

Thanks in advance

Calling a method with Ajax and returning a view

$
0
0

<div>I have a method Show which returns a view Show with a model. I use that model to populate two Kendo grids.</div> <div>In the Show view,  I have a button which on click, sends a model from the view to a method Save in the controller. </div> <div>Due to the fact that I call the Save method via an ajax call, I cannot return a view in the Save method. </div> <div> </div> <div>I tried two solutions.</div> <div> </div> <div>I tried to create a third method, let's call it Test for the sake of the argument and I tried to use </div> <div>RedirectToAction from Save and redirect it to Test but I found out that RedirectToAction does not work with an ajax call.  </div> <div> </div> <div>I decided to try with a partial view but it's also not working.</div> <div></div> <div>

public ActionResult SaveFile(List<Model> model, int type)  
        {  
               //code shortened for brevity  
               return PartialView(model, type);  
         } 

This also does not work. I am kind of stuck with this internship task I got with an existing .net core app and I am not sure how to proceed. 

How to get Machine IPAddress from ubuntu using c#

$
0
0

I trying to get IP Address to using below code, but if it's multicast nic how will get

public static List<string> GetAllLocalIPv4(NetworkInterfaceType type)
{
return NetworkInterface.GetAllNetworkInterfaces()
.Where(x => x.NetworkInterfaceType == type && x.OperationalStatus == OperationalStatus.Up)
.SelectMany(x => x.GetIPProperties().UnicastAddresses)
.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(x => x.Address.ToString())
.ToList();
}

Adding additional related Entities to ApplicationUser

$
0
0

I am working on streamlining the number of calls in my application and I want to add related entities to the ApplicationUser on login.

Right now the best I could come up with was to add properties I need to the Claims.  but having to call User.FindFirst("Value").Value gets to be a pain.

Example:

I have a related entity called CurrentAccount, and then also UserAccountAssociations.

These related entities are in my DBContext, but they aren't in my IdentityDbContext.  

I want to be able to access these properties anytime by using User.CurrentAccount.Id or User.CurrentAccount.Name, and so on, in a controller, razor page code behind or the .cshtml itself, anywhere in the application.

Is this possible?

Dockerizing my asp.net core app

$
0
0

I have two .net core application that use similar DAL and POCO classes. am using code first.

So I created the DAL as a seperate project so it can be called as a library in both of my project.

Now I want to dockerize it. am finding it hard to do this. Because my docker container can not find the dll of the two project.

The first librayr is called libary.dll

second is called dal.dll

Here is my docker file

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY . .

FROM build AS publish
RUN dotnet publish "InstantSettlement.Api.csproj" -c Release -o /app
COPY log4net.config /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "InstantSettlement.Api.dll"]

How do I make my docker file get to see this library. Please I did not reference as a project. I added the libraries as an Assemblies dependencies.

Please what do I do. the libaries are in difference folder solution. becos the have their seperate repos.

If there were in the same solution folder it would be much easier. but it different .

Advice me please.


JSON Views in .net - Cancel @jsonIgnore in specific method

Help needed in documentation

$
0
0

Hi,

Core Version: 2.2

i have implemented the swagger for the documentation in my project. but i would need to implement a security for the documentation url. Basically,  there should be a username password for API and once its authenticated, the documentation page has to be called. over there, based on the username, i would need to show the API routes. since, we will give diff creds for different vendor, showing / hiding routes may vary. so, please let me know how to implement this in asp.net core 2.2 with swagger. please share me in case of any example.

Unexpected INSERT statement conflict with the FOREIGN KEY error after create action

$
0
0

Hi,

In my project I have models like Categories -> Subcategories -> NestedCategories which are familiar to you.

Models

 public class Category
    {
        public Category()
        {
            Subcategories = new HashSet<Subcategory>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<Subcategory> Subcategories { get; set; }
    }
 public class Subcategory
    {
        public Subcategory()
        {
            Posts = new HashSet<Post>();
NestedCategories = new HashSet<NestedCategory>(); } public int Id { get; set; } public string Name { get; set; } public Category Category { get; set; } public int CategoryId { get; set; } public ICollection<Post> Posts { get; set; }
public ICollection<NestedCategory> NestedCategories { get; set; } }
public class NestedCategory
    {
        public NestedCategory()
        {
            Posts = new HashSet<Post>();
} public int Id { get; set; } public string Name { get; set; } public ICollection<Post> Posts { get; set; } public Subcategory Subcategory { get; set; } public int SubcategoryId { get; set; } }

In my adminController you can see actions that create these objects

        //Category
        [HttpGet]
        public async Task<IActionResult> CreateCategory()
        {
            MenuViewModel menuModel = new MenuViewModel();
            menuModel.Categories = await _samirDbContext.Categories.ToListAsync();
            return View(menuModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreateCategory(Category category)
        {
            if (ModelState.IsValid)
            {
                _samirDbContext.Categories.Add(category);
                await _samirDbContext.SaveChangesAsync();
                MenuViewModel menuModel = new MenuViewModel();
                menuModel.Categories = await _samirDbContext.Categories.ToListAsync();
                return RedirectToAction(nameof(CreateCategory));
            }
            else
            {
                ModelState.AddModelError("", "Couldn't create");
                return View();
            }
        }

    
        //Subcategory 

        [HttpGet]
        public async Task<IActionResult> CreateSubcategory()
        {
            MenuViewModel menuModel = new MenuViewModel();
            menuModel.Subcategories = await _samirDbContext.Subcategories.ToListAsync();
            menuModel.Categories = await _samirDbContext.Categories.ToListAsync();
            menuModel.CategoryList = await _samirDbContext.Categories.Select(a => new SelectListItem()
            {
                Value = a.Id.ToString(),
                Text = a.Name
            }).ToListAsync();

            return View(menuModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreateSubcategory(Subcategory subcategory)
        {
            if (ModelState.IsValid)
            {
                _samirDbContext.Subcategories.Add(subcategory);
                await _samirDbContext.SaveChangesAsync();
                MenuViewModel menuModel = new MenuViewModel();
                menuModel.Subcategories = await _samirDbContext.Subcategories.ToListAsync();
                menuModel.Categories = await _samirDbContext.Categories.ToListAsync();
                menuModel.Subcategory = await _samirDbContext.Subcategories.LastOrDefaultAsync();
                menuModel.CategoryList = await _samirDbContext.Categories.Select(a => new SelectListItem()
                {
                    Value = a.Id.ToString(),
                    Text = a.Name
                }).ToListAsync();

                return RedirectToAction(nameof(CreateSubcategory));
            }
            else
            {
                ModelState.AddModelError("", "Couldn't create");
                return View();
            }

        }
  
        //Nested

        [HttpGet]
        public async Task<IActionResult> CreateNested()
        {
            MenuViewModel menuModel = new MenuViewModel();
            menuModel.NestedCategories = await _samirDbContext.NestedCategories.ToListAsync();
            menuModel.Subcategories = await _samirDbContext.Subcategories.ToListAsync();
            menuModel.SubcategoryList = await _samirDbContext.Subcategories.Select(a => new SelectListItem()
            {
                Value = a.Id.ToString(),
                Text = a.Name
            }).ToListAsync();

            return View(menuModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreateNested(NestedCategory nested)
        {
            if (ModelState.IsValid)
            {
                MenuViewModel menuModel = new MenuViewModel();
                menuModel.NestedCategories = await _samirDbContext.NestedCategories.ToListAsync();
                menuModel.Subcategories = await _samirDbContext.Subcategories.ToListAsync();
                menuModel.NestedCategory = await _samirDbContext.NestedCategories.LastOrDefaultAsync();
                menuModel.SubcategoryList = await _samirDbContext.Subcategories.Select(a => new SelectListItem()
                {
                    Value = a.Id.ToString(),
                    Text = a.Name
                }).ToListAsync();

                _samirDbContext.NestedCategories.Add(nested);
                await _samirDbContext.SaveChangesAsync();
                return RedirectToAction(nameof(CreateNested));
            }
            else
            {
                ModelState.AddModelError("", "Couldn't create");
                return View();
            }

        }
    

When I create subcategory, it is successfully crerated while I do the same logic for nestedCategory, I face the following SQL Exception:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_NestedCategories_Subcategories_SubcategoryId". The conflict occurred in database "SamirDb", table "dbo.Subcategories", column 'Id'.

While creating nestedCategpry, I do not insert anything to subcategory table, it just takes its SubcategoryId from selectListItem in LINQ like I did for subcategopry when selecting relevant categoryId. In Database, all subcategories have their Ids, and everyting is ok. So what might cause this?

Here is the view of NestedCategory creation

@model Samirad.Models.ViewModels.MenuViewModel<section class="container-fluid"><section class="buttonpanel"><h6 style="font-weight:bold">Yeni Kateqoriya</h6></section><section class="posts listed"><div class="post-container"><div class="row"><div class="col-lg-3 col-md-4 col-sm-6 col-12"><form method="post" asp-action="CreateNested" asp-controller="Admin"><div asp-validation-summary="ModelOnly"></div><label asp-for="NestedCategory.Name" style="width: 85px">Ad</label><input asp-for="NestedCategory.Name" class="postinput" type="text"><br><span asp-validation-for="NestedCategory.Name"></span><label asp-for="NestedCategory.Subcategory.Name" style="width: 85px">Category</label><select asp-for="NestedCategory.SubcategoryId" asp-items="@Model.SubcategoryList" id="cat"><option value="">Subkateqoriya secin</option></select><br><button class="push" type="submit">Yarat</button> </form><br /><a asp-action="AdminAccount" asp-controller="Admin">Admin Panele qayit</a></div><div class="col-lg-3 col-md-4 col-sm-6 col-12"><table style="width:280px"><tr><th class="mytab">Alt-submenyu</th><th class="mytab">Dəyiş</th><th class="mytab">Sil</th></tr>
                        @foreach (NestedCategory item in Model.NestedCategories)
                        {<tr><td class="mytab">@item.Name</td><td class="mytab"><a asp-action="EditNested" asp-controller="Admin" asp-route-id="@item.Id">Dəyiş</a></td><td class="mytab"><a asp-action="DeleteNested" asp-controller="Admin" asp-route-id="@item.Id">Sil</a></td></tr>
                        }</table></div><div class="col-lg-3 col-md-4 col-sm-6 col-12"></div><div class="col-lg-3 col-md-4 col-sm-6 col-12"></div></div></div></section></section>

Please, help me we this issue.

Thanks in advance

unit of work compiled query in ef core 3x

$
0
0

this code working in ef core 2 

 private static Func<TContext,int, Task<TEntity>> _getById =
           EF.CompileAsyncQuery((TContext context,int id) =>
               context.Set<TEntity>()
                  .AsNoTracking()
                  .Where(s => s.Id == id)
                  .FirstOrDefault());

        private static Func<TContext, AsyncEnumerable<TEntity>> _getAll =
           EF.CompileAsyncQuery((TContext context) =>

              context.Set<TEntity>().AsNoTracking()
            );

but does not running in ef core 3 

i want to use below method but it has error

   private static Func<ClinicContext, AsyncEnumerable<T>> _getAll =
             EF.CompileAsyncQuery((ClinicContext context) => context.Set<T>().AsNoTracking());

------------------------------------------------------

Cannot implicitly convert type 'System.Func<Core3.Models.ClinicContext, System.Collections.Generic.IAsyncEnumerable<T>>' to 'System.Func<Core3.Models.ClinicContext, AsyncEnumerable<T>>' [Core3]csharp(CS0029)

ChartJSCore. Charts in ASP.Net Core

$
0
0

Hi ,

I'm trying to use charts in my ASP.Net core web application. I found this interesting https://github.com/mattosaurus/ChartJSCore.

After downloading the Nuget Package. I added the Chartcontroller and the Chart view folder with its index. and (Data, Dataset, Base) in my Model folder. Also, The plugins folder which contain (PluginDynamic) file.

everything seems ok except that the following lines in the actions of controller

  1. Data data = new Data(); //This line give me the following error : CS0118 error 'Data' is a namespace but is used like a type.
  2. Data = new List<double>() { 11, 16, 7, 3, 14 } //This line give me the following error : CS0266 cannot implicitly convert type 'system.collections.generic.list<double>' to 'system.collections.generic.IList<double?>'. An explicit conversion exist.

Any help or guides is much appreciated.

Thank you in advance. 

 

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>