Quantcast
Viewing all 9386 articles
Browse latest View live

Class Library Tag Helper for Partial Pages not working in ASP.NET Core Razor Pages application

As part of my work on an ASP.NET Core 3.1 Razor Pages web application, I created several custom Tag Helpers. Once I had all of these working the way I wanted and expected (as part of the ASP.NET Core 3.1 application), I moved the Tag Helpers to a Razor Class Library (.NET Standard 2.1), so I could use the custom Tag Helpers in other applications.

That is where I ran into a problem with a Tag Helper to render a Partial Page using the PartialTagHelper class:

TypeLoadException: Could not load type 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.IViewBufferScope' from assembly 'Microsoft.AspNetCore.Mvc.ViewFeatures, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.

The constructor for the PartialTagHelper class requires the IViewBufferScope parameter noted in this error and is passed into the custom Tag Helper code via Dependency Injection.

In the ASP.NET Core 3.1 Razor Page, the custom Tag Helper code requires a 'using' reference to the Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers namespace.

In the Razor Class Library, the custom Tag Helper code requires a 'using' reference to the Microsoft.AspNetCore.Mvc.ViewFeatures.Internal namespace. 

I also tried using .NET Standard 2.0 and 2.1 as well as .NET Core 3.1 Class Libraries.  In all of these situations, the Class Library required references to Microsoft.AspNetCore.Mvc.ViewFeatures version 2.2.0 and Microsoft.AspNetCore.Razor version 2.2.0 in order to compile.

So, the error sounds like ASP.NET Core 3.1 Razor Page is injecting the 3.1.3 Microsoft.AspNetCore.Mvc.ViewFeatures assembly and this does not contain the IViewBufferScope parameter from the correct assembly.

Is there a way to resolve this?

Thanks


Aspnetcore react project startup detection error: Unable to connect because the target computer actively refused.

<div>info: Microsoft.Hosting.Lifetime[0]</div> <div>      Application started. Press Ctrl+C to shut down.</div> <div>info: Microsoft.Hosting.Lifetime[0]</div> <div>      Hosting environment: Development</div><div>info: Microsoft.Hosting.Lifetime[0]</div> <div>      Content root path: C:\JN_Poj</div> <div>fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]</div> <div>      An unhandled exception has occurred while executing the request.</div> <div>System.Net.Http.HttpRequestException: Failed to proxy the request to http://localhost:51524/, because the request to the proxy target failed. Check that the proxy target server is running and accepting requests to http://localhost:51524/.</div> <div> </div> <div>The underlying exception message was '由于目标计算机积极拒绝,无法连接。'.Check the InnerException for more details.</div> <div> ---> System.Net.Http.HttpRequestException:由于目标计算机积极拒绝,无法连接。</div> <div> ---> System.Net.Sockets.SocketException (10061): 由于目标计算机积极拒绝,无法连接。</div> <div>   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)</div><div>   --- End of inner exception stack trace ---</div> <div>   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)</div> <div>   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)</div> <div>   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)</div> <div>   at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)</div> <div>   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)</div> <div>   at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)</div> <div>   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)</div> <div>   at Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task`1 baseUriTask, CancellationToken applicationStoppingToken, Boolean proxy404s)</div> <div>   --- End of inner exception stack trace ---</div> <div>   at Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task`1 baseUriTask, CancellationToken applicationStoppingToken, Boolean proxy404s)</div> <div>   at Microsoft.AspNetCore.Builder.SpaProxyingExtensions.<>c__DisplayClass2_0.<<UseProxyToSpaDevelopmentServer>b__0>d.MoveNext()</div><div>--- End of stack trace from previous location where exception was thrown ---</div> <div>   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)</div> <div>   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)</div> <div>   at IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)</div> <div>  at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)</div> <div>   at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)</div> <div>   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)</div> <div>   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)</div> <div>   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)</div> <div>   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)</div> <div>   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)</div>

OAuth token management with background service

I am creating an IHostedService by implementing the BackgroundService interface for a service that will run on an IIS server.  This service is going to call other api endpoints that have various authentication and authorization schemes.  One in particular requires using OAuth Authentication Code.

I need some advice on how to manage the authentication and refresh tokens for this service.  Since this service will be running in the background and not having user interaction, i will have to seed the authentication and refresh tokens and my plan is to store these in an Azure KeyVault.  The background service will then manage updating the tokens and storing them in Key Vault when they become expired.  So, two main questions:

1.  Does this approach of storing the authentication and refresh tokens in Key Vault seem like a feasible and secure approach?

2.  Since this one API needs human interaction to get the initial authentication and refresh tokens, are there any suggestions on how to seed this information in Key Vault?

Any suggestions are very much welcome.  Thanks in advance for your assistance.

Load Image from Another Drive

Hi 
i want show my images from another drive and dont want show from wwwroot folder 

my project is on C://........  but i want get images from D:/test/.......

how to set url for img src to show it ? 

i set this url for src

</img src="D:\test\wwwroot\Files\FileManage\Image\@item.Image">



but cant find it because the url is added https://localhost:44329/

https://localhost:44329/D:/test/wwwroot/Files/FileManage/Image/98dd730b-b9ca-4157-976c-2d2aa02d124f.jpg

how to read image from other drive ?

input type="date" can't show value when my modal form start

hello,

when my view start alla data are show correctly while when open my modal form with button i grid, only releaseDate field not show.

Why ? Where is my error ?

thanks

stefano

@model IEnumerable<Movie>

@(Html
    .Grid(Model)
    .Build(columns =>
    {
        columns.Add(model => model.Title).Titled("Title");
        columns.Add(model => model.ReleaseDate).Titled("ReleaseDate").Formatted("{0:d}");
        columns.Add(model => model.Genre).Titled("Genre");
        columns.Add(model => model.Price).Titled("Price");
        columns.Add(model => $"<button data-id=\"{model.Id}\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\" " +$"data-title=\"{model.Title}\" data-releaseDate=\"{model.ReleaseDate}\" data-genre=\"{model.Genre}\" data-price=\"{model.Price}\">Edit</button>").Encoded(false);
    })
)<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="exampleModalLabel">Edit</h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button></div><form method="post"><div class="modal-body"><div class="form-group"><label for="recipient-title" class="col-form-label">Title:</label><input type="text" class="form-control" id="recipient-title" name="title"><input type="hidden" id="recipient-id" name="id" /></div><div class="form-group"><label for="recipient-releaseDate" class="col-form-label">ReleaseDate:</label><input type="date" class="form-control" id="recipient-releaseDate" name="releaseDate" /></div><div class="form-group"><label for="recipient-genre" class="col-form-label">Genre:</label><input type="text" class="form-control" id="recipient-genre" name="genre" /></div><div class="form-group"><label for="recipient-price" class="col-form-label">Price:</label><input type="text" class="form-control" id="recipient-price" name="price" /></div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button><input type="submit" class="btn btn-primary" value="Save" /></div></form></div></div></div>

@section scripts{
    <script>$('#exampleModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);
            var id = button.data('id');
            var title = button.data('title');
            var releaseDate = button.data('releaseDate');
            var genre = button.data('genre');
            var price = button.data('price');
            var modal = $(this);
            modal.find('.modal-body input[name="id"]').val(id);
            modal.find('.modal-body input[name="title"]').val(title);
            modal.find('.modal-body input[name="releaseDate"]').val(releaseDate);
            modal.find('.modal-body input[name="genre"]').val(genre);
            modal.find('.modal-body input[name="price"]').val(price);
        })</script>
}

Stefano

Modal dialog not working (Razor)

Hi,

I am sorry I am totally new at .NET Core 3.1 and razor pages and there seems to be very few information about Core 3.1 and Razor.

I am trying to show a modal dialog through AJAX to add clients, but is not working, all I get is the same form duplicated:

This is my partial view (AddPartial.cshtml):

@page
@model ClienteModel<div class="modalHeader"><div class="modalLogo"><asp:Image runat="server" ImageUrl="~/content/images/modal_logo.png" alt="" Width="24" style="margin-top:8px" /></div><div class="modalTitle">Add new client</div></div><form asp-page-handler="AddPartial"><div class="mppwrapper">

This is my Cliente.cshtml.cs:

public PartialViewResult OnGetAddPartial()
        {
            return new PartialViewResult
            {
                ViewName = "~/core/cliente/AddPartial",
                ViewData = new ViewDataDictionary<Cliente>(ViewData, new Cliente  { })
            };
        }

This is my Cliente.cshtml:

<div id="modal-placeholder"></div><span class="m-nav__link-text" data-toggle="ajax-modal" data-url="@Url.Page("Cliente", "_AddPartial")" id="btnnewcli">Add new</span>$(function () {
                var placeholderElement = $('#modal-placeholder');$('[data-toggle="ajax-modal"]').on('click', function (event) {
                    var url = $(this).data('url');$.get(url).done(function (data) {
                        placeholderElement.html(data);
                        placeholderElement.find('.modal').modal('show');
                    });
                });
            });

This is my model (Cliente.cs):

public class Cliente
    {

        public Int32 Id { get; set; }
        public string name { get; set; }
}

Any ideas what could be wrong?

Atualização ASP.NET Core 2.0 para 3.1 - API não recebe mais os parâmetros do método POST

Senhores, boa tarde.

Pesquisei muito antes de abrir esse post, inclusive aqui, neste fórum. Encontrei dúvidas parecidas as quais tentei adaptar ao meu caso porem sem sucesso.

A questão é a seguinte:

Foi desenvolvida uma API em ASP.NET Core 2.0, mas por algumas solicitações do cliente, necessitei migrar para a versão 3.1. Existe uma SPA em Angular 7 que faz a requisição à API através de um método POST passando os parâmetros para a API que retornava um conjunto de dados para aplicação montar a tela. Após a atualização parou de funcionar! Por isso, gostaria de pedir a ajuda de vocês, por que, eu já esgotei as minhas tentativas.

No Controller da API está da seguinte maneira:

[HttpPost]
[Route("api/[controller]")]
public IGResult Post(Filtro filtro)
{
Console.WriteLine("filtro: " + filtro);
var app = new IgApplication();
return app.getInstrucoes(filtro);
}

E no angular se encontra dessa forma:

return this._http.post<IgResult>(environment.url + 'api/IG', this.Filtro, options)

Ao debugar a API, percebo que os dados do parâmetro body chegam nulos. Já tentei das seguintes maneiras abaixo, mudar a implementação do POST na API porém sem sucesso:

//public async Task<IActionResult> Post([FromBody] Filtro pessoa)
//public HttpResponseMessage Post(Filtro pessoa)
//public async Task<ActionResult<IList<Todo>>> Create([FromBody]TodoCreateViewModel model)
//public Task<IActionResult> Post([FromBody] Filtro filtro)
//public ActionResult<Filtro> Post([FromBody] Filtro filtro)
//public HttpResponseMessage Post(Filtro filtro)
//public string Post([FromBody] Filtro filtro)
//public IActionResult Post([FromBody] Filtro filtro)
//{
//var app = new IgApplication();
//return app.getInstrucoes(filtro);
//return null;// Json(filtro);
//}
//public async System.Threading.Tasks.Task<string> Post(HttpRequestMessage request)
//{
// string body = await request.Content.ReadAsStringAsync();
// return body;
//}

Por isso se possível, gostaria muito de contar com a colaboração de vocês.

Desde já muito obrigado!

Show text beside on the same line

I have the following code inside my razor view inside an Asp.Net MVC core web application:-

<td><input asp-for="b1" type="text" class="form-control">%</td>

where the % sign will be shown on a new line, so can i show the % and the input field beside each other on the same line?


Can't Run my app has IIS Express

Ok so I did some settings when trying to deploy asp.net core web app locally sometimes ago. Suddenly i just noticed that on vs when I try to run my app.

I can not run app with the IIS Express option. I have to pick the the name of the app when I want to debug.

https://pasteboard.co/J54l9V9.jpg   check that link for a snapshot so you understand what am saying

This is a snapshot of my vS to explain the problem.  Please this is a problem for me. Cos if I have multiple website on my solution I I cant run every thing at once.

How do I fix this problem. Got a problem with multiple sites and I need to run every thing at once so I can monitor all from IIS instance cos they all depend on each other to work well.

The record is not being displayed from related table

Hi

I have two table Authors and Country. Country is the foreign key table of Author. When list authors , the corresponding country is not being showed. Please help in my sql

Country table
CountryId  CountryName 
  1          UK
  2          Australia
Authors
AuthorId    FirstName   LastName    CountryId 
 1            Thomas     Philiph       1
 2            John       Varghese      2

Model

public class Country
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CountryId { get; set; }

        [Required]
        [MaxLength(50, ErrorMessage = "Country must be up to 50 characters in length")]
        public string CountryName { get; set; }
        [JsonIgnore]
        public virtual ICollection<Author> Authors { get; set; }
    }

public class Author
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int AuthorId { get; set; }

        [Required]
        [MaxLength(100, ErrorMessage ="First Name cannot be more than 100 characters")]
        public string FirstName { get; set; }

        [Required]
        [MaxLength(200, ErrorMessage = "Last Name cannot be more than 200 characters")]
        public string LastName { get; set; }

        [ForeignKey("CountryId")]
        public int CountryId { get; set; }
        public  Country Country { get; set; }
    }

Repository. When I try to list all the Authors with  their  country  details, the country  is being showed as null. How can I list the  related country records also with their details

public class AuthorRepository : IAuthorRepository
    {
        private BookStoreDbContext _db;

        public AuthorRepository(BookStoreDbContext db)
        {
            _db = db;
        }


	public ICollection<Author> GetAuthors()
        {var authorlist = _db.Authors.OrderBy(a => a.LastName).ToList(); // Country is not showed here
            return authorlist 
        }
}

Suggestion Needed: Syncing Mailbox through API

Hello, 

I am creating an app that sends and receives emails through different hosting providers IMAP + Office + Gmail. Now the problem that I am facing is that a user can send an email at any point of time irrespective of the background job is syncing after a specific interval. So for example

The user send's an email 3:12 PM and meanwhile, the job is scheduled for 3:14 PM. Now as of the UX experience I have to show the user immediately that email is sent and should be displayed in the respective folders in our application. 

Now, what should I do should the sent email be inserted in the database immediately and then later on when job runs we check if this email is already in the system.

Regards

Cannot implicitly convert type error

My mode class and modelDTO  is given below. When I am trying to assign an object entity to another object entity the error is coming  Please help in my code

Author

 public class Author
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int AuthorId { get; set; }

        [Required]
        [MaxLength(100, ErrorMessage ="First Name cannot be more than 100 characters")]
        public string FirstName { get; set; }

        [Required]
        [MaxLength(200, ErrorMessage = "Last Name cannot be more than 200 characters")]
        public string LastName { get; set; }

        [ForeignKey("CountryId")]
        public int CountryId { get; set; }
        public  Country Country { get; set; }
    }


Model

AuthorDTO
 public class AuthorDto
    {
        public int AuthorId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int CountryId { get; set; }
        public CountryDto Country { get; set; }
        public IEnumerable<SelectListItem> CountryList { get; set; }
    }
public IActionResult GetAuthors()
        {
            var authors = _authorRepository.GetAuthors();

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

            var authorsDto = new List<AuthorDto>();

            foreach (var author in authors)
            {
                authorsDto.Add(new AuthorDto
                {
                    AuthorId = author.AuthorId,
                    FirstName = author.FirstName,
                    LastName = author.LastName
                    Country = author.Country // Here error is coming 'Cannot implicitly convert type error'
                });
            }

GetAuthor Method

  public ICollection<Author> GetAuthors()
        {
            var authorList = _db.Authors.Include(c => c.Country).ToList();
        }

Issue with session in asp.net core session middle ware.

Hi,

we have an issue with the Session Middleware in asp.net core . actually if i am trying to access application from one host it's working fine. then with same host if i am trying to access the another application. the [previously opened ] / first application's session getting cleared . 

what will be issue with session/ session middleware . please advise.

using below in application processing pipeline

UseSession();

UseCookiePolicy

and the service is configured using  - 

CookiePolicyOptions

AddSession

can i pass ioption to an inherited class as the poco?

i have this

 public SomeClass(IOptions<MyOptions> options) : base(options as BaseConfiguration)

but it won't work because it IOption of and not just the class (the base class isn't an ioption)is there a way to pass it as the class and not as ioptions?

Question about an issue with a MVC project and views

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?


Upload image array with other fields, not just images.

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.

Help needed in Authentication

Hello Guys,

I am working in .net core 2.2 and i have a requirement that i will need to consume 3rd arty SOAP service and they have certificate based authentication. This is pretty  standard in .net framework by creating the soap service as proxy and in the webconfig we have this .

<system.serviceModel><behaviors><endpointBehaviors><behavior name="MC.behavior.rdy"><clientCredentials><clientCertificate findValue="MycompanyDomain.com" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /><serviceCertificate><defaultCertificate findValue="clientDomain.com" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /></serviceCertificate></clientCredentials></behavior></endpointBehaviors></behaviors><bindings><customBinding><binding name="UserServiceSoapBinding"><textMessageEncoding messageVersion="Soap12" /><security defaultAlgorithmSuite="Basic128Rsa15" allowSerializedSigningTokenOnReply="true" authenticationMode="MutualCertificate" securityHeaderLayout="Lax" messageProtectionOrder="SignBeforeEncrypt" messageSecurityVersion="WSSecurity10WSTrust2005WSSecurityPolicy11BasicSecurityProfile50" requireSecurityContextCancellation="false"></security><httpsTransport manualAddressing="false" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous" realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false" useDefaultWebProxy="true" /></binding></customBinding><basicHttpBinding><binding name="ITransactionProcessor"><security mode="Message" /></binding></basicHttpBinding></bindings><client><endpoint address="https://clientDomain.com/services/UserService2009" binding="customBinding" bindingConfiguration="UserServiceSoapBinding" contract="UserService" name="UserServicePort" behaviorConfiguration="MC.behavior.rdy" ><identity><userPrincipalName value="IIS APPPOOL\NETWORK SERVICE" /></identity></endpoint> </client></system.serviceModel>

how do i achieve this in .net core 2.2. is there a way?  i can add the connected service to create proxy. but no idea about this certificate based authentication implementation while consuming the soap service in .net core.  Please help me in this and in case if there is any sample please do share it here. it wold be much helpful to me. 

Value from asp-route-id dynamically

Hey guys,

How can I select an item on <select> object and send it's value to an asp-route-id?

I have this code:

<div class="col-8 p-0" style="margin-left:-16px;"><select id="slctProcedure" class="form-control selectpicker" data-live-search="true" asp-items="@ViewBag.Procedures" onchange="onSelectedIndexChanged(this)"><option value="-1" selected>---------</option></select></div><div class="col-2"><a id="btnAddProcedure" class="btn btn-outline-primary" asp-controller="CustomerService" asp-action="AddProcedureToAppointment" asp-route-id="@ProcedureID" style="border-radius:30px;"><i class="fas fa-plus"></i></a></div><script>    function onSelectedIndexChanged(value) {        var textValue = value.options[value.selectedIndex].value;        document.getElementById("ProcedureID").value = textValue;         $("btnAddProcedure").attr("asp-route-id", document.getElementById("ProcedureID").value);            }</script>

My controller:

public async Task<IActionResult> AddProcedureToAppointment(string id){
...
}

But when I click in <a> I only get zero (initial value of @ProcedureID) not the value on <select>. What I'm doing wrong? How can I do this?

How can I do this?

What is the alternative to Ajax.BeginForms in Asp.net MVC core

I think in asp.net MVC core we no more have the option to use Ajax.BeginForms .. so what is the alternative for Ajax.BeginForm inside asp.net mvc core?

Ajax form is not working inside my razor view

I have the following code inside my razor view:-

<form method="get" data-ajax="true" data-ajax-url="/Submission/Create" data-ajax-method="get" data-ajax-update="#panel" data-ajax-failure="failed"><div class="form-group"><input type="submit" value="Submit" class="btn btn-primary" /></div></form>

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>}

which generated the following markup:-

<form method="get" data-ajax-failure="failed" data-ajax-update="#panel" data-ajax-method="get" data-ajax-url="/Submission/Create" data-ajax="true"><div class="form-group"><input class="btn btn-primary" type="submit" value="Submit"></div></form>

now the result i should have got is that when i click on the submit button to call the /Submission/Create/ action method, but what is happening is that the form will refresh the current page /Home/Index/ so can anyone advice?

Viewing all 9386 articles
Browse latest View live


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