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

.Net Core MVC with React and Webpack

$
0
0

Is there a way to have ASP .Net Core MVC with React components and Webpack? Visual studio react project teamplate is providing react app with API, but requirement is different.

My requirement is need to have normal ASP. Net Core MVC view with react components in it. I want to use the React page/components into my MVC view.

There are some sample available where we need to bundle the react components and then use the bundle in code. I cant bundle every change and use during development. So is there any way or any sample available kindly share.


Validating the entity already exist

$
0
0


I have an POST method to create an entity. In this table email is primary key and other columns are user information (name,surname, etc.)
I have two questions, please answer both :)
1) If customer send an email that already exist in database, API returns 500. But I want to return 400 and say "this email already in use". How can I do that when I trying to add new user to database.?
2) Is it true approach to make email as primary key for database design?

Im using ef core3.1 and asp.net core 3.1

zh-CN resource dll is not generated when build web app in Linux server

$
0
0

I have been localizing the our .Net Core (2.1) MVC Project with Resource files and CookiesCultureRequestPattern. We have 3 additional languages now such as korean, Japnees and Chines.

The issue is when build and publish the solution in the Linux deployment server. only zh-CN folder and resource.dll has not been degenerated. But in my local Windows machine does all.

What should i do for forcing to generate the dll when build the solution?

Thanks

Not all code Paths Return a value

$
0
0

How can I initialize the variable query  before try --catch statement. Please help

 public Comedian[] GetComedians()
        {
            try
            {
                _logger.LogInformation($"Getting all comedians");
                var query = _db.Comedians
                            .OrderBy(c => c.LastName);
                //return query.ToArray();

            }
            catch(Exception ex)
            {

            }
          return query.ToArray(); // How can I return the variable query here

          
        }

Could static thread be stopped in Kestrel on Linux without manual abort?

$
0
0
public class HomeController {

public static Thread Thread = new Thread(new ThreadStart(Work));

public ViewResult Index()
{
if(!Thread.IsAlive && DateTime.Now < new DateTime(2020,12,31))
    Thread.Start()

return View();

}

public static void Work()
{
}

}

What reasons could lead to Thread abort in this piece of code rather than manual server machine stop on Linux if we call Index only once a year?

package manager console help needed using visual studio 2019

$
0
0

When I run the following command in package manage console(VS 2019). I get the following error.

Add-Migration InitialMigration
The name 'InitialMigration' is used by an existing migration.
PM>

can somebody throw light on this? I am trying to use one project which was used in other machine to learn and tweak this project. Actually this command need to sync database schema and application model classes. At the moment my project doesn't have db - i only have VS files project which was taken from other machine.

i know basic C#, asp.net and a bit of asp.net core.

Cheers

Sathya

What is the difference between Icollection and IQueryable ?

$
0
0

Hi

I just confused with  which one is the best to use to list the  record fast  either Icollection or IQueryable . What is the difference between two? Please can you advise me 

Regards

Pol 

Intellisense won't suggest asp-for Tag Helper properties

$
0
0

In my View Model code, asp-for correctly shows me that "LostMisspelled" is not a member of the Data Model by underlining it in red.  It also correctly accepts "Lost" and "@Model.Lost" as asp-for properties.

However, while Intellisense suggests Lost as I type "@Model.L" it refuses to suggest Lost as I type "Lo" on the first line of code.  However, once I've finished typing Lost, Intellisense doesn't flag it (it shouldn't) so it knows Lost is just fine.

So the question is, why won't it auto-suggest or auto-complete Lost as I'm typing it, the way it does with @Model.Lost ?

<label asp-for="Lost"></label>
<label asp-for="LostMisspelled"></label>
<input asp-for="@Model.Lost" />


Razor intellisense not working on empty solution!

$
0
0

Hi

I've created an empty asp.net core 3.1 (vs 2019) empty solution, but my problem is that i can not use razor intellisense feature!

Also i've found this link which say add Microsoft.AspNetCore.Razor.Tools package, but i could not find this package!

Can anybody help me what's wrong & how to solve this issue?

Thanks in advance

ASP.NET core razor pages c# equivalent to php echo and die

$
0
0

In a model behind I want to see if a variable has what it is supposed to have.

In php I can:

echo $myvariable;
die;

In the model behind I tried:

Response.Write(somevar);
Response.End();

And got:

Severity Code Description Project File Line Suppression State
Error CS1061 'HttpResponse' does not contain a definition for 'Write' and no accessible extension method 'Write' accepting a first argument of type 'HttpResponse' could be found (are you missing a using directive or an assembly reference?) pcore31 C:\Users\kpskl_000\source\repos\pcore31\pcore31\Pages\petnew\Create.cshtml.cs 58 Active


Severity Code Description Project File Line Suppression State
Error CS1061 'HttpResponse' does not contain a definition for 'End' and no accessible extension method 'End' accepting a first argument of type 'HttpResponse' could be found (are you missing a using directive or an assembly reference?) pcore31 C:\Users\kpskl_000\source\repos\pcore31\pcore31\Pages\petnew\Create.cshtml.cs 59 Active

Okay, in a .net core project, how do I echo then die? 

Reference to type IdentityBuilder claims it is defined in microsoft.aspnetcore.identity but it could not be found

$
0
0

I'm getting this error when upgraded csproj to netstandard1.2 then come NuGet package upgrade in csproj.  This csproj is a dependency DLL to the 3 WebApp csproj.

Error --> Reference to type IdentityBuilder claims it is defined in microsoft.aspnetcore.identity but it could not be found

I'm a bit stump & not having much luck after 2 days of Google search but found this one link at https://forums.asp.net/t/2162412.aspx?Error+with+aspnetcore+3+1+identity+

public static void AddPaymentsForPortal<TRequestContext, TUserContext>(this IServiceCollection services, IConfiguration configuration, IEnumerable<EmbeddedAssemblySource> embeddedViewAssemblies, PortalRoleType roleType)

{

     services.AddIdentity<ApplicationUser, IdentityRole<Guid>>()

    .AddEntityFrameworkStores<ApplicationContext, Guid>()

    .AddDefaultTokenProviders();

}

public class ApplicationContext : IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid>

{

    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)

    {

    }

 protected override void OnModelCreating(ModelBuilder builder)

{

}

public class ApplicationUser : IdentityUser<Guid>, IUser

{

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)

    {

    }

}

<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />

<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="3.1.3" />

<PackageReference Include="Microsoft.AspNetCore.DataProtection.AzureStorage" Version="1.0.2" />

<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.2" />

<PackageReference Include="Microsoft.AspNetCore.HttpOverrides" Version="1.1.2" />

<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />

<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="1.1.3" />

<PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />

<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />

<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="1.1.2" />

<PackageReference Include="Microsoft.Extensions.Caching.Redis" Version="1.1.2" />

<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.3" />

<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="3.1.3" />

<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="1.1.1" />

<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.3" />

public async Task OnPostAsync()

$
0
0

I am working with some generated code, had to modify it for image upload.  And I am more used to something like this:

        public void OnPost()
        {
            string petid = Request.Form["petid"];
            string petname = Request.Form["petname"];
            string odate = Request.Form["odate"].ToString();
            var ocheck = Request.Form["ocheck"].ToString();
            string postvalues = petid + "|" + petname + "|" + odate + "|" + ocheck;
            Lqtest upet = new Lqtest();
            upet.Updatepipe(postvalues);
            ViewData["updated"] = "Record updated";

        }
// just test db and testing with delimited and with json in another model.

And custom model:

        public void Updatepipe(string uplist)
        {

            string[] plist = uplist.Split('|');

            string petid = plist[0];
            string petname = plist[1];
            string odate = plist[2];
            string ocheck = plist[3];


            int vpetid = Convert.ToInt32(petid);

            Dbcon ob = new Dbcon();
            using (var db = ob.OpBuilder())
            {
                var entity = db.Pet.Where(x => x.PetID == vpetid).First();
                entity.PetName = petname;

                entity.Odate = !string.IsNullOrEmpty(odate) ? (DateTime?)DateTime.Parse(odate) : null;

                entity.Ocheck = ocheck == "1" || ocheck == "on" ? true : false;

                db.SaveChanges();
            }

        }

However the generated code starts with:

        public async Task<IActionResult> OnPostAsync()
        {
         ///   more code /////

Inside of the method I cannot use:

string pic = Request.Form["Upload"];  //  does not work
  if (pic == null).....

///  tried

    if (string.IsNullOrEmpty(pic) ......



// however I can use
    if (Upload == null).....

Why doesn't standard Request.Form work in this generated method.

Note I am used to writing my own classes for crud, and new to using and having to modify the generated code.

Thanks

why id=0 when make it integer but if string it get value ?

$
0
0

I work on asp.net core 2.2 really when assign value to id on url as id=5

it display on debugging id=0 although i write value beside id 

i write my URL as below 

 [HttpGet]
        [Route("GetAllFilters/{id}")]
        public IActionResult GetAllFilters(int id)
        {

            try
            {
                //string[] s = id.Split('=');
               
               // int Reportid = Convert.ToInt32(s[1]);
                var getfilters = _reportservice.GetReportFilter(id);
               
                return Ok(getfilters);
            }
            catch (Exception ex)
            {

                return NotFound(ex.Message);
            }

        }

I write on my URL as below 

http://localhost:61265/api/GetAllFilters/report/id=5

so why id=0 this is my question and how to solve that

i send get request from google chrome browser  visual studio 2017

RazorEngine.NetCore showing error in MVC .net core project....help

The entity type 'AllVM' requires a primary key to be defined for VM with EF Core

$
0
0

Hi

I'm trying to return multiple different non related models in one view as aggregate interface page (each one in html tab) with Entity Framework Core (Core 2.1).

Holidays model:

    public class Holidays
    {
        public int Id { get; set; }

        public string Name{ get; set; }
    }

Actions model:

    public class Actions
    {
        public int Id { get; set; }

        public string Name{ get; set; }
    }

AllVM model:

    public class AllVM
    {
        public IList<Holidays> Holidays { get; set; }
        public IList<Actions> Actions{ get; set; }
    }

ApplicationDBContext:

public virtual DbSet<Actions> Actions { get; set; }
public virtual DbSet<Holidays> Holidays { get; set; }
public virtual DbSet<AllVM> AllVM { get; set; }

Controller:

    public class MyController : Controller
    {
        private readonly ApplicationDbContext _context;

        public MyController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> AllIndex()
        {
            var all = _context.AllVM.Include(s => s.Holidays).Include(s => s.Actions).AsQueryable();

            return View(await all.ToListAsync());
        }

But this scenario gives me the error:

InvalidOperationException: The entity type 'AllVM' requires a primary key to be defined.

I don't want to define a primary key for the ViewModel, I want only to return 2 or more non-related models in AllIndex view each one of them in a tab.

How please?


Target Project does not match your migration assembly.Please help

$
0
0

In  my project , I am keeping DbContext  in a separate project from the  web app project. This is my program structure is given below. But when I give Add-Migration the following error is coming

Your target project 'LibraryBook' doesn't match your migrations assembly 'LibraryBook.DataAccess'. Either change your target project or change your migrations assembly.
Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("LibraryBook")). By default, the migrations assembly is the assembly containing the DbContext.
Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.

LibraryBook[WebApplication]                   -> Views                  ->Appsetting.json                 ->Startup.cs
                  ->program.cs



LibraryBook.DataAccess [ another project]
            Data [folder]  -> ApplicationDbContext.cs 

Appsetting.Jason

{"ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=LibraryBooks;Trusted_Connection=True;MultipleActiveResultSets=true"
  },"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
    }
  },

DbConext.cs

using System;
using System.Collections.Generic;
using System.Text;
using LibraryBook.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace LibraryBook.DataAccess.Data
{
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

How can I add new folder created inside the project in GitHub Repository

$
0
0

I have added new repository in GitHub and I have added the project in to that repository. But newly created folder does not being updated in to that repository. How can I add new folder of the project in to the GitHub repo.

Pol

I Have problem in ICollection ASP CORE

$
0
0

Good morning, I have a question about something I am trying to develop, the project is in ASP CORE 3.1 MVC. I have 2 identities one to one and the other (which is the one with problems) from one to many. What happens is that I am adding a company (Company Model) and those responsible for this company (Company Responsable Model) which are the following:

publicpartialclassEmpresa{publicintEmpresaId{get;set;}publicstringNombreEmpresa{get;set;}publicstringNumeroDistribuidor{get;set;}publicstringUbicacion{get;set;}publicstringRazonSocial{get;set;}publicstringDomicilio{get;set;}publicstringTelefono{get;set;}publicstringCorreo{get;set;}publicintCantidadEmpleados{get;set;}publicstringFechaAlta{get;set;}publicstringHoraAlta{get;set;}publicstringFechaModificacion{get;set;}publicstringHoraModificacion{get;set;}publicstringUsuarioAlta{get;set;}publicstringUsuarioModificacion{get;set;}publicbool?Estado{get;set;}publicvirtualNaturalezaEmpresaNaturalezaEmpresa{get;set;}publicICollection<ResponsableEmpresa>ResponsableEmpresas{get;set;}}}

Model ResponsableEmpresa:

publicintResponsableEmpresaId{get;set;}publicstringPuesto{get;set;}publicstringNombre{get;set;}publicstringApellidoMaterno{get;set;}publicstringApellidoPaterno{get;set;}publicstringCorreo{get;set;}publicstringTelefono{get;set;}[ForeignKey("Empresa")]publicintEmpresaId{get;set;}publicvirtualEmpresaEmpresa{get;set;}

Now, what I try is that in the view I can add the data of the company and separate those responsible, which would be the following view:

@modelEmpresa<h1 class="text-center">Datos generales de la empresa o grupo</h1><form asp-action="Guardar" asp-controller="Empresa" method="post"><div class="form-group col"><label>Nombre de la empresa:</label><input type="text" asp-for="NombreEmpresa"class="form-control"/><span asp-validation-for="NombreEmpresa"class="text-danger"></span></div><div class="form-group col"><label>Número de distribuidor:</label><input type="text" asp-for="NumeroDistribuidor"class="form-control"/><span asp-validation-for="NumeroDistribuidor"class="text-danger"></span></div><div class="form-group col"><label>Ubicación:</label><input type="text" asp-for="Ubicacion"class="form-control"/><span asp-validation-for="Ubicacion"class="text-danger"></span></div><div class="form-group col"><label>Razón Social:</label><input type="text" asp-for="RazonSocial"class="form-control"/><span asp-validation-for="RazonSocial"class="text-danger"></span></div><div class="form-group col"><label>Domicilio:</label><input type="text" asp-for="Domicilio"class="form-control"/><span asp-validation-for="Domicilio"class="text-danger"></span></div><div class="form-group col"><label>Telefono:</label><input type="tel" asp-for="Telefono"class="form-control"/><span asp-validation-for="Telefono"class="text-danger"></span></div><div class="form-group col"><label>Correo:</label><input type="email" asp-for="Correo"class="form-control"/><span asp-validation-for="Correo"class="text-danger"></span></div><div class="form-group col"><label>Cantidad de empleados:</label><input type="number" asp-for="CantidadEmpleados"class="form-control"/><span asp-validation-for="CantidadEmpleados"class="text-danger"></span></div><div class="form-group col"><label>Cantidad de empleados:</label><input asp-for="ResponsableEmpresas.Add(@responsableEmpresa)"class="form-control"/></div>@*<h1 class="text-center">ResponsableEmpresa</h1><p><br /><br /></p><table id="myTable"class="table table-bordered text-center"><thead><tr><td scop="col">Puesto</td><td scop="col">Nombre</td><td scop="col">ApellidoMaterno</td><td scop="col">ApellidoPaterno</td><td scop="col">Correo</td><td scop="col">Telefono</td></tr></thead><tbody><tr></tr></tbody></table><br><script>function myFunction(){var table = document.getElementById("myTable");
                table.contentEditable =true;var row = table.insertRow(2);var cell1 = row.insertCell(0);var cell2 = row.insertCell(1);var cell3 = row.insertCell(2);var cell4 = row.insertCell(3);var cell5 = row.insertCell(4);var cell6 = row.insertCell(5);
                cell1.innerHTML ="Ingresar Puesto";
                cell2.innerHTML ="Ingresar Nombre";
                cell3.innerHTML ="Ingresar Apellido Materno";
                cell4.innerHTML ="Ingresar Apellido Paterno";
                cell5.innerHTML ="Ingresar Correo ";
                cell6.innerHTML ="Ingresar Teléfono";}function myDeleteFunction(){
                document.getElementById("myTable").deleteRow(2);}function showTableData(){//gets tablevar oTable = document.getElementById('myTable');//gets rows of tablevar rowLength = oTable.rows.length;//loops through rowsfor(i =0; i < rowLength; i++){//gets cells of current rowvar oCells = oTable.rows.item(i).cells;//gets amount of cells of current rowvar cellLength = oCells.length;//loops through each cell in current rowfor(var j =0; j < cellLength; j++){// get your cell info herevar cellVal = oCells.item(j).innerHTML;if(cellVal.toString()!="Puesto"&& cellVal.toString()!="Nombre"&& cellVal.toString()!="Nombre"&& cellVal.toString()!="Apellido Materno"&& cellVal.toString()!="Apellido Paterno"&& cellVal.toString()!="Correo"&& cellVal.toString()!="Telefono"){
                            alert(cellVal);}}}}</script>*@<div class="row float-right" style="margin: 10px 5px 5px 5px"><a><input type="button" onclick="myFunction()"class="btn btn-info float-right"value="Insertar"/></a></div><div class="row float-right" style="margin: 10px 5px 5px 5px"><a><input type="button" onclick="myDeleteFunction()"class="btn btn-danger float-right"value="Borrar"/></a></div><div class="row float-right" style="margin: 10px 5px 5px 5px"><a><input type="button" onclick="showTableData()"class="btn btn-danger float-right"value="Leer"/></a></div><div class="row"><button type="submit"class="btn btn-primary float-right">Guardar</button></div></form>

The idea is that a number of managers can be added, but I cannot find a way to add it that when returning to the controller brings the information of Company Responsible .

Basically the idea is to pass an array from the view to the controller, but I have the problem handling the ICollection

Thanks a lot!

Problem for using Asp.net c# and html mixing code

$
0
0

I tried to use below code in asp.net but there is error in html tags like and and say it could not find begin tag. but begin tag is in first if. the errors are in between line 44 to 52.

@{string n ="";int j =0;foreach(var item inModel.RelatedProduct){if(item.ProductId!= n)
                j =1;else
                j =0;if(j==1){<div class="modal fade" id="myModal" role="dialog"><div class="modal-dialog modal-dialog-centered " role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">@item.CatalogDescription</h5><button class="close" type="button" data-dismiss="modal"><span aria-hidden="true">&times;</span></button></div><div class="modal-body"><table class="table table-hover"><thead class="thead-dark"><tr><td>Customer</td></tr>}@if(j ==1|| j ==0){<tr><td>@item.CustomerName</td><td>@item.Price</td></tr>}@if(j==1){</table></div><div class="modal-footer"><button class="btn" data-dismiss="modal">Cancel</button></div></div></div></div>}}}

how to overcome overload method taking 3 arguments

$
0
0

Hi, I'm having issue while using "PasswordSignInAsync" during login process. Error message shows CS1501 No overload for method "PasswordSignInAsync" takes 3 arguments. 

my login.cshtml.cs login code

        [HttpGet]
        public IActionResult Login()
        {
            return Page();
        }

        [HttpPost]
        public async Task<IActionResult> Login(DDACWebApp.Pages.LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(account.Email, account.Password, false);

                if (result.Succeeded)
                {
                    return RedirectToAction("index", "home");
                }

                ModelState.AddModelError(string.Empty, "Invalid Login attempt");
             }
            return Page();
        }

Please let me know if I may have put blunder or lack of statement. Thank you

Viewing all 9386 articles
Browse latest View live


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