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

Question about an issue with a MVC project and views

$
0
0

Hello,

   So originally the design aspect of a site that was being developed was supposed to be the mvc app would be the site name, essentially root on IIS.  Development proceeded and everything was working good on the development side.  Well a change was made to make this a subsite (www.sitename.com/mvcapp).  After some discussion that things should work still, it was decided to push the app to the IIS server in UAT and go from there.  An issue did present itself, and we have determined a work around, but I am trying to see if there is a reason behind the issue.

   So the first thing that was notices was that when the app was launched to the first controller (Menu) that the background picture did not display.  We were able to navigate to other sections of the app and most other controllers worked without a problem (www.sitename.com/mvcapp/controller/edit, etc. )  Further inspection of the reason the background were not working and the logo was working showed the background image pulling a 404 error, where it was looking for the image at www.sitename.com/mvcapp/Menu/~/images/BackgroundImages/imagename.png.  Even more baffling was that the logo was stored in the same folder on the wwwroot and it worked.  Then it was noticed that one of the modals was not working correctly as it tried to call up a differentcontroller/index it too was getting a 404 looking at the original controller and appending the next controller onto it so it was seeing Menu/DifferentController/Index.  Now after some playing around with the images the tilde was not working, so it was replaced with a ../images/BackgroundImage/imagename.png and pushed to the server.  This worked.  The site.js was reworked so that the modal was now calling ../DifferentController/Index and it worked.

   I guess the question comes in as to why the dot dot (..) worked and the tilde (~) didn't work?  Everything that was read is that the tilde should have brought it back to the wwwroot folder.  While there is a working solution in place, it there a way to make this work with the tilde or as in the case of the modal not have a tilde or dot dot in front?


AddApiAuthorization with Angular login/register pages instead of MVC views

$
0
0

I'm using the following scaffolded example with angular and ASP.NET Identity with IdentityServer4.

dotnet new angular -o <output_directory_name>-au Individual

The implementation is amazing, because it uses the recommended code with PKCE with angular OIDC client, which I tried to do myself, but it's way more code and it doesn't look as good as Microsoft's.

I want to use angular login/register pages instead of the default MVC views. Is that possible? I'm aware that what they did is also a separate part of the project, but I still want to use angular views. My angular and ASP.NET Core projects are completely separate and I don't use services.AddSpaStaticFiles which optimizes angular and starts angular at same port with the ASP.NET Core.

The connected services component Microsoft WCF web service reference provider failed.(HRESULT: 0x80131500) the project format is incorrect

$
0
0

I upgraded my project from dotNetCore 2.2 to 3.0 two weeks ago. Now I want to add a Webservice to it

But I got this error when I clicked on Microsoft WCF Web Service Reference ProviderI am using visual studio 2019

None of the suggestions about Microsoft WCF Web Service Reference Provider are the same error as mine

This is the error I got

The connected services component Microsoft WCF web service reference provider failed.(HRESULT: 0x80131500) the project format is incorrect

Can someone please suggest a fix for this? Thanks

creating razor by using loops

$
0
0

nevermind, i found an error. how to delete this post?

To register HttpClient service in configure service to call api from web application

$
0
0

I am calling the API from my web application is as given below

 public class AuthorRepositoryGUI : IAuthorRepositoryGUI
    {
        private readonly IHttpClientFactory _clientFactory;

        public AuthorRepositoryGUI(IHttpClientFactory clientFactory) 
        {
            _clientFactory = clientFactory;
        }
}


  public async Task<AuthorDto> GetAuthors()
        {
            var url = "http://localhost:2318/api/Authors/"
            AuthorDto author = new AuthorDto();
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<AuthorDto>(jsonString);

            }

It is working fine right now. But I want to  call the API repository by registering the client in configure service. So I would like to register the  client service as given below. Is it possible. If possible how can i call the API from repository, Please can you help me

public void ConfigureServices(IServiceCollection services)
{
     services.AddHttpClient<IAuthorRepositoryGUI, AuthorRepositoryGUI>(client =>
    {
        client.BaseAddress = new Uri("https://localhost:44379/");
    });
}

// If I create the client in configure service as given above . how can I call the API in the given repository  here
 public async Task<AuthorDto> GetAuthors()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<AuthorDto>(jsonString);

            }

             
            return author;
        }

i have problem a Project ASP Core

$
0
0

hi Every One nice to meet you Iam Happy for Register in this Site i have big problem for two week I Can not find solution for this error i work on project mvc core and make OrderMasterDetails and i want to save in database

But something wear is happining MasterDetails is Save well in dataBase but orderDetails I can not save in database Also i turn on break point but I can not See any Error .

Notice: i use Ajax to send data and ajax work good without Error But I think Something wrong in my Controller I can not Know What is it???

and here my View And Controller and my DB

Controller

[HttpPost]

public IEnumerable<OrderMasterDetails> addorder([FromBody]OrderMasterDetails ordermasterdetail)

{

OrderMaster orderMaster = new OrderMaster();

orderMaster.Order_Code = ordermasterdetail.Order_Code;

orderMaster.Hours = DateTime.Now.Hour.ToString();

int discount = 0;

int.TryParse(ordermasterdetail.discount, out discount);

orderMaster.discount = discount;

orderMaster.DateAdded = DateTime.Now;

orderMaster.BranchID = int.Parse(ordermasterdetail.BranchID);

orderMaster.Order_Kind_ID = int.Parse(ordermasterdetail.Order_Kind_ID);

int tax = 0;

int.TryParse(ordermasterdetail.tax, out tax);

orderMaster.tax = tax;

_Context.orderMasters.Add(orderMaster);

_Context.SaveChanges();

var dborder_Master = _Context.orderMasters.SingleOrDefault(c => c.Order_ID == orderMaster.Order_ID);

dborder_Master.Order_Code = ordermasterdetail.Order_Code + dborder_Master.Order_ID.ToString();

foreach (var item in ordermasterdetail.lstProducts)

{

OrderDetails orderDetails = new OrderDetails();

orderDetails.Order_ID = orderMaster.Order_ID;

orderDetails.Product_ID = int.Parse(item.Product_ID);

orderDetails.Product_Price = float.Parse(item.Product_Price);

orderDetails.Product_Quantity = int.Parse(item.Product_Quantity);

orderDetails.Unit_ID = int.Parse(item.Unit_ID);

_Context.orderDetails.Add(orderDetails);

_Context.SaveChanges();

}

return null;

}

View

@model OrderMasterDetails

@{

ViewData["Title"] = "Create";

Layout = "~/Views/Shared/_layout.cshtml";

}

<h1>Create Order</h1>

<meta http-equiv="refresh" content="0; url=https://www.enable-javascript.com" />

</noscript>*@

<form method="post">

<table class="table table-bordered">

<tr>

<td>

<label class="control-label">Code</label>

</td>

<td>

<input value="@ViewBag.Order_Code" id="Order_Code" class="form-control" />

</td>

</tr>

<tr>

<td>

<label class="control-label">Order kind</label>

</td>

<td>

<select disabled="disabled" id="Order_Kind_ID" class="form-control" asp-items="ViewBag.Order_Kind_ID"></select>

</td>

</tr>

<tr>

<td>

<label class="control-label">Branch</label>

</td>

<td>

<select id="BranchID" class="form-control" asp-items="ViewBag.Branch_ID"></select>

</td>

</tr>

<tr>

<td>

<label class="control-label">tax</label>

</td>

<td>

<input id="tax" class="form-control" />

</td>

</tr>

<tr>

<td>

<label class="control-label">discount</label>

</td>

<td>

<input id="discount" class="form-control" />

</td>

</tr>

</table>

<table class="table table-borderless">

<tr>

<th>

product

</th>

<th>

unit

</th>

<th>

quantity

</th>

<th>

price

</th>

<th>

</th>

</tr>

<tr id="trrows">

<td>

<select id="Product_ID" class="Product_ID form-control" asp-items="ViewBag.Product_ID"></select>

</td>

<td>

<select id="Unit_ID" class="Unit_ID form-control" asp-items="ViewBag.Unit_ID"></select>

</td>

<td>

<input id="Product_Quantity" class="Product_Quantity form-control" />

</td>

<td>

<input id="Product_Price" class="Product_Price form-control" />

</td>

<td>

<button type="submit" id="addtocart" name="addtocart" class="btn btn-primary">add</button>

</td>

</tr>

</table>

</form>

<table id="tblrows" class="table table-hover">

</table>

<hr />

<button asp-action="addorder" type="submit" id="save" name="save" class="btn btn-primary">Save All</button>

@section Scripts {

<script src="~/lib/jquery/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function () {

$("#addtocart").click(function () {

var product_id = document.getElementById("Product_ID").value;

var trrow = $("#trrows").clone().removeAttr("id");

$('.Product_ID', trrow).val(product_id);

$("#addtocart", trrow).addClass('remove').html('Remove').removeClass('btn-primary').addClass('btn-danger');

$("#tblrows").append(trrow[0]);

});

$("#tblrows").on("click", ".remove", function () {

$(this).parents("tr").remove();

});

});

</script>

<script type="text/javascript">

$(document).ready(function () {

$("#save").click(function () {

var lstitems = [];

jQuery("#tblrows tr").each(function () {

var item = {

"Product_ID": $('.Product_ID').val(),

"Product_Price": $('.Product_Price').val(),

"Product_Quantity": $('.Product_Quantity').val(),

"Unit_ID": $('.Unit_ID').val()

}

lstitems.push(item);

});

var order_code = $('#Order_Code').val();

var branch_id = $('#BranchID').val();

var tax = $('#tax').val();

var discount = $('#discount').val();

var order_kind_id = '1';

$.ajax({

url: '/OrderMasterDetails/addorder',

type: 'POST',

// data: formData,

dataType: 'json',

headers: {

'Content-Type': 'application/json;charset=utf-8'

},

data: JSON.stringify({

"Order_Code": order_code, "BranchID": branch_id, "tax": tax, "discount": discount, "Order_Kind_ID": order_kind_id, "lstProducts": lstitems

}),

success: function (data) {

// your code in success

alert('saved');

},

error: function (responseData, textStatus, errorThrown) {

alert('POST failed.');

}

});

});

});

</script>

@{await Html.RenderPartialAsync("_ValidationScriptsPartial");

}

}

Model

public class OrderMasterDetails

{

public string Order_Code { get; set; }

public string BranchID { get; set; }

public string tax { get; set; }

public string discount { get; set; }

public string Order_Kind_ID { get; set; }

public List<ListProducts> lstProducts { get; set; }

}

public class ListProducts

{

public string Product_ID { get; set; }

public string Unit_ID { get; set; }

public string Product_Quantity { get; set; }

public string Product_Price { get; set; }

}

i saved Master in db but I can not Save OrderDetails

Please i want any help and At The End Really thanks For EveryOne

 

SqlException error when trying to implement pagination in .net core web api

$
0
0

Hello All,

I have these two pieces of code to implement pagination in .net core.

The first piece is a class as follows:

public class QueryParameters
{
    const int _maxSize = 100;
    private int _size = 50;

    public int Page { get; set; }

    public int Size 
    {  
        get { return _size; }
        set { _size = Math.Min(_maxSize, value); }
    }
}

The second one is my HttpGet code:

private readonly NSContext _context;

    public UsersController(NSContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<IActionResult> GetAllUSers([FromQuery] QueryParameters queryParameters)
    {
        IQueryable<User> users = _context.User;
        users = users
            .Skip(queryParameters.Size * (queryParameters.Page - 1))
            .Take(queryParameters.Size);
        return Ok(await users.ToArrayAsync());
    }

but when I run the program I get this error:

Does anybody have a solution for this problem?

Thanks in advance.

Trying to merge contexts Identity core and Application Context

$
0
0

Hi I have two contexts my identity core and application context I am using .net core 3.1 but I am having an issue where it says the following.

public class AppManagerDBContext : IdentityDbContext
    { 
        public AppManagerDBContext(DbContextOptions options) : base(options) { }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("name=DefaultConnection");
            }
        }

        public DbSet<BmiInformation> BmiInformation { get; set; }

        public DbSet<WorkOuts> WorkOuts { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<BmiInformation>().ToTable("BmInformation");
        }
}

I have the context injected into the services statup configuration element.

 public void ConfigureServices(IServiceCollection services)
 {

            services.AddDbContext<AppManagerDL.AppManagerDBContext>
              (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
 ......

}
         

Any Ideas what could be wrong.

Error

The DbContextOptions passed to the AppManagerDBContext constructor must be a DbContextOptions<AppManagerDBContext>. When registering multiple DbContext types make sure that the constructor for each context type has a DbContextOptions<TContext> parameter rather than a non-generic DbContextOptions parameter.
PM> Add-Migration MyFirstMigration -Context AppManagerDBContext
Build started...
Build failed.


ASP.NET Core - XML

$
0
0

Hi,

I need your help again.

Last week I published a thread because I couldn't read the XML.

This I have already managed to do.

But now I have another problem. When I try to read the file it gives this error.(link bellow)

Error

I will put some code lines.

XML:

-<products>


-<product><id>100</id><name>Ball</name><price>15</price><quantity>2</quantity>


-<description><comment>aaa</comment></description></product></products>

MODEL:

 [Table("Table")]
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }
        public int Quantity { get; set; }

        public Description Description{ get; set; }
        
    }
   
   public class Description
    {
        [Key]
        public string DescriptionComment { get; set; }
    }

CONTROLLER:

  private List<Product> ProcessImport(string path)
        {
            XDocument xDocument = XDocument.Load(path);
            List<Product> products = xDocument.Descendants("product").Select
                (p => new Product()
                {
                   Id = Convert.ToInt32(p.Element("id").Value),
                   Name=p.Element("name").Value,
                   Quantity = Convert.ToInt32(p.Element("quantity").Value),
                   Price = Convert.ToInt32(p.Element("price").Value),
                   Description = new Description()
                   {
                       DescriptionComment= p.Element("description").Element("comment").Value
                   }
                }).ToList();
            foreach(var product in products)
            {
                var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id));
                if (productInfo != null)
                {
                    productInfo.Id = product.Id;
                    productInfo.Name = product.Name;
                    productInfo.Quantity = product.Quantity;
                    productInfo.Price = product.Price;
(I think the problem is here!) } else { db.Products.Add(product); } db.SaveChanges(); } return products; }

If you can help me I woul appreciate.

Thanks!

Best regards

Andre

Exception user unhandled

$
0
0

I keep going from appplicationdbcontext file to program files errors.

Below is the error message  I am using aspnet core mvc 3.1

System.TypeLoadException: 'Method 'Create' in type 'Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitorFactory' from assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation.'

Here is the ApplicationDBContext file 

using Bumples15.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Bumples15.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)  //here is the error
{
}
public DbSet<Product> Products { get; set; }

public DbSet<Order> Orders { get; set; }

}
}

Below is the program file;

namespace Bumples15
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

}
}

here is the startup file:

using Bumples15.Data;
using Bumples15.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Bumples15
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

services.AddControllersWithViews();

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();


services.AddScoped<RoleManager<IdentityRole>>();
services.AddScoped<IRepository<Product>, SqlBooksRepository>();
services.AddScoped<IRepository<Order>, SqlOrdersRepository>();

services.AddRazorPages();

services.AddRazorPages();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();

}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();


app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}

Some of the programs were files taken from aspnet core mvc 2.1.  But I think that I have upgraded them all.

Is that where my problem is:

Thanks

Jen

Windows Authentication in ASP.NET Core with Kestrel On Linux Plateform

$
0
0

Hello,
I am not a developer but I work with others on the implementation of windows authentication in net.core on Linux platform. Apparently, this is now possible directly with Kestrel in version 3 preview
So I tried, but without success. However, I followed the official MS documentation

"https://docs.microsoft.com/fr-fr/aspnet/core/security/authentication/windowsauth?view=aspnetcore-3.0&tabs=visual-studio=aspnetcore-3.0&tabs=visual-studio"

I tried the SDK 3.0 on two linux VMs, one in Debian 10 and the other in centOS 7.6.

I have configured my krb5.conf file correctly

I have registered my VM on my AD domain with success

I created a dot.net project with the command "dotnet new webapp --auth Windows".

I added the package "dotnet add package Microsoft.AspNetCore.Authentication.Negotiate --version 3.0.0-preview6.19307.2"

I created my SPN and keytab

setspn -S HTTP/mywebservice.coolcorp.priv pocvm

setspn -S HTTP/mywebservice@COOLCORP.COM pocvm

ktpass -princ HTTP/mywebservice.coolcorp.priv@COOLCORP.PRIV -pass myKeyTabFilePassword -mapuser COOLCORP\pocvm$ -pType KRB5_NT_PRINCIPAL -out c:\temp\pocvm.HTTP.keytab -crypto AES256-SHA1

When I test my keytab with the kinit command, it works.
kinit HTTP/mywebservice.coolcorp.priv@COOLCORP.PRIV -k -t /etc/keytab/pocvm.HTTP.keytab

I do have a kerberos ticket.

I set the location of my keytab as an environment variable.
export KRB5_KTNAME=/etc/keytab/pocvm.HTTP.keytab

I updated the startup file

namespace pocdotnet
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
            });
        services.AddMvcCore(options =>
    {
        options.EnableEndpointRouting = false; // TODO: Remove when OData does not causes exceptions anymore
    });

            services.AddRazorPages();
            services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseAuthentication();
            app.UseMvc();
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthorization();



            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

I launch my application: dotnet run

But when I display my site "mywebservice.coolcorp.priv", my username does not appear next to Hello.

Does anyone have any ideas or could they help me?

How to join two tables in Asp.net core.

$
0
0

Hi Team,

Unable to retrieve the data from two tables. 

 

        private readonly CoreDbContext _context;

        public SecSubmodulesController(CoreDbContext context)
        {
            _context = context;
        }


[HttpGet] public async Task<ActionResult<IEnumerable<SecSubmodules>>> GetSecSubmodules() { //return await _context.SecSubmodules.ToListAsync(); var varSubmodulesData = (from P in _context.SecSubmodules join C in _context.SecModules on P.ModuleId equals C.ModuleId select new SubModules { ModuleID = (long)P.ModuleId, SubModuleID = P.SubModuleId, ModuleName = C.ModuleName, SubModuleName = P.ModuleName, }); return await varSubmodulesData.ToListAsync(); }



 

internal class SubModules
    {
      //

        public long ModuleID { get; set; }
        public string ModuleName { get; set; }
        public string SubModuleName { get; set; }
        public long SubModuleID { get; set; }
         
    }

Error:

 

Severity	Code	Description	Project	File	Line	Suppression State
Error	CS0029	Cannot implicitly convert type 'System.Collections.Generic.List<sample.Controllers.SubModules>' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<sample.Models.SecSubmodules>>'	sample	D:\Angular\Service_sample \sample \Controllers\SecSubmodulesController.cs	42	Active

Self contained web API run exe from cmd

$
0
0
Hello,
I've got a self hosted web API which runs in a console, is there anyway I can run this console exe from command prompt and specify a port number to run from as an argument ? & If you can what would the command look like & do I need to change anything in my project to allow for this ?

Unable to route through Area

$
0
0

HI All,

Please can anyone help using Area Routing which is not working using ASP.NET Core 3.1

HTML Code

<div class="row"><div class="col-12">
        @Html.DropDownList("NationCase", (SelectList)ViewBag.NationList, "Select nation", new
{ onchange = "document.location.href =  '/' + this.options[this.selectedIndex].value;", @class = "form-control form-control-sm col-sm-3 mb-1", @style = "float:left;" })</div></div

C#

  [Area("Admin")]
    public class WebController : Controller
    {

        private readonly GlobalDBContext _context;


        public WebController(GlobalDBContextcontext)
        {
            _context = context;            
        }

        public IActionResult Index()
        {
            getNationList(null);
            return View();
        }


        [Route("/{id}")]
        public IActionResult Index(int id)
        {
            ViewBag.LocID = id;
            getNationList(id);
            return View();
        }




        private void getNationList(int? id)
        {
            var nationList = _context.NationMeterTop.Select(s => new { Id = s.LocationId, Value = s.Nation }).OrderBy(s => s.Value).ToList();
            ViewBag.NationList = new SelectList(nationList, "Id", "Value", id);
        }
    }

Startup.cs

  app.UseEndpoints(endpoints =>
            {
                endpoints.MapAreaControllerRoute(
                    name: "MyAreaAdmin",
                    areaName: "Admin",
                    pattern: "Admin/{controller=Home}/{action}/{id?}");

             
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

I want when user select value from dropdown it should below action method

[Route("/{id}")]
        public IActionResult Index(int id)
        {
            ViewBag.LocID = id;
            getNationList(id);
            return View();
        }

Thanks,

Shabbir

why search string 'Text6=''locations''' not work from web API and give excption but it work from sql ?

$
0
0
public DataTable GetReportDetailsSearch(string ReportID, string FromDate, string ToDate, string SearchString)
      {
          List<SqlParameter> param = new List<SqlParameter>()
          {
              new SqlParameter("@ReportID", ReportID),
              new SqlParameter("@ReportDateFrom", FromDate),
              new SqlParameter("@ReportDateTo", ToDate),
              new SqlParameter("@SearchString",SearchString),

          };

  DataTable ReportDetailsSearch = SQLDAL.ReturnDataTableByProcedure("sp_ReportDetailsGetALL", param);
          return ReportDetailsSearch;
      }



[Route("ReportDetailsSearch")]
       [HttpPost]
       public IActionResult GetSearchedData([FromBody] dynamic DataObjectSearch)
       {

           try
           {
               string ReportId = DataObjectSearch.reportID;
               string FromDate = DataObjectSearch.startdate;
               string StartDate = FromDate.Substring(0, 10);
               string todate = DataObjectSearch.enddate;
               string EndDate = todate.Substring(0, 10);
               string Searchdata = DataObjectSearch.searchstring;

               var PostSearch = _reportservice.GetReportDetailsSearch(ReportId, StartDate, EndDate, Searchdata);

               return Ok(PostSearch);


       }



When execute web api search string added to it double quotes why and how to solve issue ?


I work on web api asp.net core 2.2 I face this error


An expression of non-boolean type specified in a context where a condition is expected, near 'and'.


procedure work from SQL success as below


exec [dbo].[sp_ReportDetailsGetALL] "2028","2020-05-03","2020-05-11", 'Text6=''locations'''


exactly issue on the following line


'Text6=''locations'''


not work if as below


"'Text6=''MFG'''"


on web api i think it add double quotes on start and end so that it not work


json i passed to web api as following :

{ "startdate": "2020-05-03T22:00:00Z", "enddate": "2020-05-11T22:00:00Z", "searchstring": "'Text6=''MFG'''", "reportID": "2028" 
} 



procedure getreportdetail as following :

declare @ColumnName Nvarchar(max) = (SELECT 'select ' + STUFF((SELECT ',' + 'Text'+CONVERT(varchar(20),ReportHeaderIndex) + ' '+ '['+ReportHeader +']' 
FROM ReportHeaders where ReportID=@ReportID order by ReportHeaderIndex 
FOR XML PATH('')) ,1,1,'') + ' , convert(nvarchar(20),[ReportDate]) ReportDate From ReportDetails R where ReportDate >= ''' +@ReportDateFrom+''' and ReportDate <= '''+ @ReportDateTo +''' and R.ReportID =' + @ReportID + ' and '+@SearchString+' and IsHistory=0 order by reportdate desc ' + @SortingColumns AS Txt ) 
exec (@ColumnName) 





ASPNETCORE_ENVIRONMENT Development- Production problems

$
0
0

I have a .Net Core 2.+ app, it publishes to my shared hosting fine thru web publish, and it  worked (registering a user, data entering the SQl database) fine the first few times after i was able to publish it to remote server. Now when trying to register a new user, when hitting "Register" button, it renders the "

An error occurred while processing your request.

Development Mode

Swapping to the Development environment displays detailed information about the error that occurred....

error. According to possible fix on  https://www.tutorialsteacher.com/core/aspnet-core-environment-variable , I have gone into VS , right clicked on the project name, > Debug, and changed the ASPNETCORE_ENVIRONMENT to Production (I also did likewise on the launchsettings.json ), still the same error. 
??
Ned

How to solve async method lacks 'await' operators and will run synchronously

$
0
0

When I use the given code it shows the  warning always coming 'async method lacks 'await' operators and will run synchronously' when I  run the application. How can I solve 

[HttpGet]
public async Task<IActionResult> CreateAuthor()
{
return View();
}



InvalidOperationException: Unable to resolve service for type for API Repository Please help

$
0
0

 Hi

In my web application has two project BookWeb  and BookAPI . BookWeb is being referenced with BookApi apllication. In BookWeb project the controller name  'AuthorController' is  calling the the API controller  AuthorController action CreateAuthor(). In both project have same controller name and Action name but different name space.

When I use the same action name in both controller the following error is coming 

'InvalidOperationException: Unable to resolve service for type 'BookStoreAPI.Repository.IRepository.IAuthorRepository' while attempting to activate 'BookStoreAPI.Controllers.AuthorsController'.

If I use different actioname in BookWeb  from API controller it will work.

Can I use the same action name  and same controller name in different namespace? Please can you help.

BookAPI
namespace BookStoreAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorsController : Controller
    {
         private IAuthorRepository _authorRepository;
        private IBookRepository _bookRepository;
        private ICountryRepository _countryRepository;
        public AuthorsController(IAuthorRepository authorRepository, IBookRepository 
         bookRepository,
            ICountryRepository countryRepository)
        {
            _authorRepository = authorRepository;
            _bookRepository = bookRepository;
            _countryRepository = countryRepository;
        }

       public IActionResult CreateAuthor([FromBody]Author authorToCreate)
        {
            if (authorToCreate == null)
                return BadRequest(ModelState);

            if (!_countryRepository.CountryExists(authorToCreate.CountryId))
            {
                ModelState.AddModelError("", "Country doesn't exist!");
                return StatusCode(404, ModelState);
            }

            authorToCreate.Country = _countryRepository.GetCountry(authorToCreate.CountryId);

            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            if (!_authorRepository.CreateAuthor(authorToCreate))
            {
                ModelState.AddModelError("", $"Something went wrong saving the author " +$"{authorToCreate.FirstName} {authorToCreate.LastName}");
                return StatusCode(500, ModelState);
            }

            return CreatedAtRoute("GetAuthor", new { authorId = authorToCreate.AuthorId }, authorToCreate);
        }

    }
}

In BookWeb Controller

namespace BookWeb.Controllers
{
    public class AuthorsController : Controller
    {
        IAuthorRepositoryGUI _authorRepository;
        ICountryRepositoryGUI _countryRepository;
        ICategoryRepositoryGUI _categoryRepository;

        public AuthorsController(IAuthorRepositoryGUI authorRepository, ICountryRepositoryGUI countryRepository,
            ICategoryRepositoryGUI categoryRepository)
        {
            _authorRepository = authorRepository;
            _countryRepository = countryRepository;
            _categoryRepository = categoryRepository;
        }

[HttpGet]
        public async Task<IActionResult> CreateAuthor()
        {
            return View();
        }

In startup file

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseStatusCodePages();
            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}"
                    );
            });

Upload image array with other fields, not just images.

$
0
0

I currently have the following:

@page
@model pcore31.AddimgModel

@{
    Layout = null;
}

<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Addimg</title></head><body><h4>Petimg</h4><hr /><div class="row"><div class="col-md-4"><form enctype="multipart/form-data" method="post"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Petimg.PetName" class="control-label"></label><input asp-for="Petimg.PetName" class="form-control" /><span asp-validation-for="Petimg.PetName" class="text-danger"></span></div><div class="form-group"><label asp-for="Upload1" class="control-label"></label><input asp-for="Upload1" class="form-control" type="file" /></div><div class="form-group"><label asp-for="Upload2" class="control-label"></label><input asp-for="Upload2" class="form-control" type="file" /></div><div class="form-group"><input type="submit" value="Create" class="btn btn-primary" /></div></form></div></div><div><a asp-page="Index">Back to List</a></div>

    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }</body></html>

And code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using pcore31.Models;
using pcore31.Helpers;
using System.IO;

namespace pcore31
{
    public class AddimgModel : PageModel
    {
        private readonly pcore31.Models.DatabaseContext _context;
        private IWebHostEnvironment _environment;
        private string fileName;
        //private string filename;

        public AddimgModel(pcore31.Models.DatabaseContext context, IWebHostEnvironment environment)
        {
            _context = context;
            _environment = environment;

        }

        public IActionResult OnGet()
        {
            return Page();
        }

        [BindProperty]
        public Petimg Petimg { get; set; }
        [BindProperty]
        public IFormFile Upload1 { get; set; }
        [BindProperty]
        public IFormFile Upload2 { get; set; }


        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            int k = -1;
            int j = 0;
            string[] items = new string[2];
            string[] newfile = new string[2];
            Lqtest csql = new Lqtest();
            var idcount = csql.Idcount();
            string stringcount = idcount.ToString();
            foreach (IFormFile postpic in Request.Form.Files)
            {
                k = k + 1;
                j = j + 1;
                string sj = j.ToString();
                if (postpic == null)
                {
                    items[k] = "";
                    newfile[k] = "";
                }
                else
                {
                    items[k] = postpic.Name.ToString();
                    int thisid = idcount + j;
                    string thiscount = thisid.ToString();

                    var filename = $"{postpic.FileName}";
                    Array getparts = StrHelper.SplitString(filename);
                    string parta = getparts.GetValue(0).ToString();
                    string partb = getparts.GetValue(1).ToString();

                    newfile[k] = parta + thiscount + "." + partb;
                    var file = Path.Combine(_environment.ContentRootPath, "wwwroot\\images\\upload", newfile[k]);
                    using (var fileStream = new FileStream(file, FileMode.Create))
                    {
                        await postpic.CopyToAsync(fileStream);
                    }
                }


            }
            Petimg.PetName = StrHelper.Ucfirst(Petimg.PetName);
            Petimg.Petpic1 = $"{newfile[0]}";
            Petimg.Petpic2 = $"{newfile[1]}";
            _context.Petimg.Add(Petimg);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }
    }
}

This all works.

My question is how do I convert this to an array, like:

@page
@model pcore31.AddimgModel

@{
    Layout = null;
}

<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Addimg</title></head><body><h4>Petimg</h4><hr /><div class="row"><div class="col-md-4"><form enctype="multipart/form-data" method="post"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Petimg.PetName" class="control-label"></label><input asp-for="Petimg.PetName" class="form-control" /><span asp-validation-for="Petimg.PetName" class="text-danger"></span></div><div class="form-group"><input asp-for="Upload[]" class="form-control" type="file" /></div><div class="form-group"><input asp-for="Upload[]" class="form-control" type="file" /></div><div class="form-group"><input type="submit" value="Create" class="btn btn-primary" /></div></form></div></div><div><a asp-page="Index">Back to List</a></div>

    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }</body></html>

How do I change the binding to reflect an array of files:

// Currently I have:
       [BindProperty]
        public Petimg Petimg { get; set; }
        [BindProperty]
        public IFormFile Upload1 { get; set; }
        [BindProperty]
        public IFormFile Upload2 { get; set; }


//  And what would this change to:
foreach (IFormFile postpic in Request.Form.Files)  ???

Thanks

And I am not wanting

type="file" multiple 

I want the array, as files can come from more than one folder.

Sorting MVC View Results (really more of an architectural issue)

$
0
0

My controller has an [HttpGet] index() action that displays a form with several inputs that are not bound to my database.  For example there is a drop-down containing all the years from 1960 to 2020.  When a user selects one, the form is posted and the [HttpPost] action method finds every item in the database from that year.  Works great!

I would like a user to be able to sort the results by item name.  I would also eventually like to do pagination.

1.  Is there a Javascript/CSS library that will do all this so I can just plug it in?

2.  If not, I have attempted to code it.  However I can't get the data to persist when I do something like this:

<a asp-action="Index" asp-route-sortorder="@ViewBag.NameSortParm">Sort by Airline / Bag Name</a>

in order to trigger this

            switch (sortorder)
            {
                case "airline_desc":
                    baglist = baglist.OrderByDescending(s => s.Airline).ToList();
                    break;
                case "year":
                    baglist = baglist.OrderBy(s => s.Year).ToList();
                    break;
                case "year_desc":
                    baglist = baglist.OrderByDescending(s => s.Year).ToList();
                    break;
                default:
                    baglist = baglist.OrderBy(s => s.Airline).ToList();
                    break;
            }

which calls the Index() get method, meaning I've lost the filtered data from the model.  It no longer has any idea that the data from the dropdown was say, 2005.  I'm guessing that the original form shouldn't post and should instead use a querystring.  is that a better way to go?  Even so, it still doesn't help me retain only the 2005 data when sorting.

I suppose I could cache the results (now that I know how to do so) but it seems like there's a better, clearer way to do so.

Viewing all 9386 articles
Browse latest View live


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