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

how to migrate wcf in .net core

$
0
0

Hi team

i am migarting asp.net project to ,net core 3.1

how to migrate wcf  here , shall i migrate wcf or use rest api for this or any other better suggestion

please suggest


Asp.Net Core Mvc JsonResult Not Triggered

$
0
0

publicclassQuote
    {         
        publicstringFullName{get;set;}

        publicstringEmail{get;set;}

        publicstringPhone{get;set;}

        publicstringBudget{get;set;}      

        publicstringMessage{get;set;}
    }

$("#submit").on('click',function(){$.ajax({ url:'/Home/QuoteMessageSend', type:"POST", dataType:'json', data:$("#QuoteForm").serialize(), error:function(xhr, textStatus, error){ console.log(xhr.statusText); console.log(textStatus); console.log(error);}});});

<form id="QuoteForm">
                <p>
                    <input id="fullName" asp-for="FullName" placeholder="Full Name"class="contact-item"/>
                    <span id="fnoutput"></span>
                </p>
                <p>
                    <input id="email" asp-for="Email" placeholder="Email" class="contact-s-item" />
                    <span id="emoutput"></span>
                </p>
                <p>
                    <input id="phone" asp-for="Phone" placeholder="Phone" class="contact-s-item" />
                    <span id="phoneoutput"></span>
                </p>
                <p>
                    <select asp-for="Budget" class="contact-l-item">
                        <option value="" disabled selected>Budget</option>
                        <option value="200-1000">€200-800</option>
                        <option value="800-4000">€800 - €4000</option>
                        <option value="4000-12000">€4000-12000</option>
                        <option value="12000+">€12000+</option>
                    </select>
                    <span id="budgetoutput"></span>
                </p>
                <p>
                    <textarea id="message" asp-for="Message" placeholder="Your Ideas" class="contact-m-item"></textarea>
                    <span id="messageoutput"></span>
                </p>
                <button id="submit" type="button">Submit Now</button>
            </form>

          

[HttpPost]
        publicJsonResultQuoteMessageSend(Quote quote)
        {
            QformCheck(quote);
            if(qfncheck && qemcheck&& qphonecheck && qbdcheck&& qmsgcheck)
            {
                using(MySqlConnection connection=newMySqlConnection("Server=localhost; Database=dbname; Uid=root; Pwd=123456; SSL Mode=none;"))
                {
                    using(MySqlCommand cmd=newMySqlCommand("INSERT INTO quotes(FullName, Email, Phone, Budget, Message) VALUES(@fn, @em, @ph, @bdg, @msg)", connection))
                    {
                        connection.Open();
                        cmd.Parameters.AddWithValue("@fn", quote.FullName);
                        cmd.Parameters.AddWithValue("@em", quote.Email);
                        cmd.Parameters.AddWithValue("@ph", quote.Phone);
                        cmd.Parameters.AddWithValue("@bdg", quote.Budget);
                        cmd.Parameters.AddWithValue("@msg", quote.Message);
                        cmd.ExecuteNonQueryAsync();
                        connection.Close();
                    }
                }
                returnJson(new{ data = quote, success=true, responseText=""});
            }
            else
            {
                returnJson(new{ data = quote, success=true, responseText=""});
            }                

        }

While this code works flawlessly in local, it doesn't work when I broadcast. When I check the item and look at it, all the necessary code I can see it being called. I thought the problem might be in the database connection, I created a simple sample table and pulled data on the server works smoothly. However, when I register to the database with JsonResult, it does not get into the database almost on the server side. It does not give any errors. Just looking at the item with check item again, I could see that it wrote 404 bad request. Apart from that I have there is nothing.

Need help setting up multi select option checkbox list for my ASP.NET Core Razor Website

$
0
0

I have been trying several code samples from forums but they all seem to use a List of a class type that gets data saved in, while I am just trying to use a list of strings from data for the days of the week, so users can choose their preferred days of the week for personal training.

Here are some of the few things I have tried:

Model I have tried using 

        public List<string> DailyAvail { get; set; } = new List<string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

PageModel

        public List<string> DailyAvail { get; set; } = new List<string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            var emptySession= new TrainingRoutineVM();
            var entry = _context.Add(emptyPtSession);
            entry.CurrentValues.SetValues(TrainingRoutineVM);
            await _context.SaveChangesAsync();

            PopulatePtDropDownList(_context, emptyPtSession.PersonalTrainingID);

            return RedirectToPage("./Index");
        }

View

<label class="form-check-label"><ul>
                    @for (var i = 0; i < this.Model.DailyAvail.Count(); i++)
                    {<li><input type="checkbox" asp-for="@Model.TrainingRoutineVM.PersonalTraining.Product.IsChecked" /><label asp-for="@Model.TrainingRoutineVM.PersonalTraining.Product.IsChecked">@Model.DailyAvail[i].</label><input type="hidden" asp-for="@Model.TrainingRoutineVM.TrainingRoutineID" /><input type="hidden" asp-for="@Model.DailyAvail[i]" />
                            @Html.ValidationMessageFor(x => x.DailyAvail)</li>
                    }</ul></label>

which gave me an entity relationship error when I try to add migration because List<string> is not compatible with EF.

Then I tried Using this in the page model and also view Model only but i think then it will not save the results onto the database, if the properties do not exist in both the model and the view model, so I was thinking of trying to add this in the model with a string property with the same name as the List item in view model

public string DailyAvail { get; set; }

But I am not sure how to dynamically convert into type string when adding to the database, I think when seeding the database I did something like:

DailyAvail =  string.Join(",", DailyAvail);

but yeah when adding the list items in the database I am not sure how to do that.

So yeah how would I implement an option to multi select days of the week, so user can select a couple of options, which is supposed to be saved to the user's order when they checkout.

How to access ViewData from external javascript ?

$
0
0

Hi

i've use this external javascript function to access ViewData variable(s) :

function deleteOrderItem(orderID) {
    if (confirm('Are you sure want to delete this item?')) {$.ajax({
            type: "POST",
            url: "DeleteOrder",
            data: { id: orderID },
            success: function () {
                setTimeout(function () {
                    debugger;
                    var personID = "@ViewData['_personID']";
                    viewItem(personID);
                }, 500)
            }
        });
    }
}

But at runTime, when i'm using developer tools, the personID contains @ViewData[_personID] as text and not accessing real viewData which i've set in my action method!

Here is my action method :

// POST: Orders/Delete/5
        [HttpPost]
        public async Task<IActionResult> DeleteOrder(int id)
        {
            var orders = await _dbContext.Orders.FindAsync(id);

            ViewData["_personID"] = orders.PersonId;

            _dbContext.Orders.Remove(orders);
            await _dbContext.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

Where is the problem & how to solve it?

Thanks in advance

cycles or multiple cascade paths in ef core

$
0
0

Hi,

i have this error in update database , whats problem ?

ProductInfo.cs

  [Key]
        public int ProductInfo_ID { get; set; }

  [InverseProperty("ProductInfo")]
        public virtual IEnumerable<SimilarProduct> SimilarProduct { get; set; }


        [InverseProperty("SimilarProduct1")]
        public virtual IEnumerable<SimilarProduct> SimilarProduct2 { get; set; }

SimilarProduct.cs

 [Key]
        public int ID { get; set; }

        [ForeignKey("ProductInfo")]
        public int ProductInfo_ID { get; set; }
        public ProductInfo ProductInfo { get; set; }


        [ForeignKey("SimilarProduct1")]
        public int ProductSimilarID { get; set; }
        public ProductInfo SimilarProduct1 { get; set; }

Error
Introducing FOREIGN KEY constraint 'FK_SimilarProduct_tb_ProductInfo_tb_ProductSimilarID' on table 'SimilarProduct_tb' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.

i set this but its not worked 

          builder.Entity<SimilarProduct>()       // THIS IS FIRST
.HasOne(u => u.ProductInfo).WithMany(u => u.SimilarProduct).IsRequired().OnDelete(DeleteBehavior.Restrict);

            builder.Entity<SimilarProduct>()
       .HasOne(pt => pt.SimilarProduct1)
       .WithMany(p => p.SimilarProduct2)
       .HasForeignKey(pt => pt.ProductSimilarID).OnDelete(DeleteBehavior.Restrict); 



First project in an ASP.NET Core 3.1 application

$
0
0

Hello,

I have successfully completed my first project in an ASP.NET Core application using Connector/NET Core to explore the possibility to run this application on any .NET Core

This is the tutorial

This project work correctly on http://localhost:XXXX/Tablename

Now I need publish the project on the windows server 2008 for sharing on the web this work

On the server I have installed dotnet-sdk-3.1.300-win-x64.exe

I have copied the folder and file from project local to remote server c:\inetpub\wwwroot\aspnetcore\mvccore

but if get on the browser the link http://mywebsite/aspnetcore/mvccore/views/tablename/Index.cshtml the return is page not found

isn't copying the local file and folders on the server enough for the project to work?

I am server administrator... maybe do I have to configure IIS?

can the new configuration create problems to the existing one on IIS?

how to do resolve this?

can you help me, please?

Fail to add multiple attachments to mail message in net core web app

$
0
0

Hi,

I try to construct and send an email message in a web net core app. The message need to have maximal 3 attachments, provided by the user who navigates the site. First is mandatory, and at least one from the two remaining attachments is also mandatory.

If I attach only one (e.g. first) attachment, all is ok. But when I attach at least 2 attachments, I have an error.

The relevant portions of code are bellow (the model, the view, and the controller). At the very bottom is the error:

/*Relevant part of model*/

public class Inscrieri.Inima.Models
{
//
        public IFormFile CopieCN { get; set; }
        public IFormFile CopieCIT { get; set; }
        public IFormFile CopieCIM { get; set; }
//
}


/*Relevant part of view*/

<div class="separator"></div><div><strong>Certificat de Nastere Copil</strong><p> (in format *.jpg sau *.png):</p></div><div>
                @Html.TextBoxFor(model => model.CopieCN, new { type = "file" })</div><div><strong>Act de Identitate Tata:</strong><p> (in format *.jpg sau *.png):</p></div><div>
                @Html.TextBoxFor(model => model.CopieCIT, new { type = "file" })</div><div><strong>Act de Identitate Mama:</strong><p> (in format *.jpg sau *.png):</p></div><div>
                @Html.TextBoxFor(model => model.CopieCIM, new { type = "file" })</div><div class="separator"></div><div class="clearfix"></div><div><input type="submit" value="Trimite" /></div><div class="separator"></div><span style="color:green">@ViewBag.Message</span>


/*Relevant part of controller*/

        [HttpPost]
        public IActionResult Index(EmailModel model)
        {
            using (MailMessage mm = new MailMessage("sender.email@gmail.com", "first.recipient@email.com, second.recipient@email.com"))
            {
                mm.Subject = "Cerere de inscriere pentru: " + model.Prenume + " " + model.Nume;
                mm.Body = "Va rog sa aprobati inscrierea copilului " + model.Prenume + " " + model.Nume + " nascut(a) la data de " + model.DataNasterii + ", avandu-i ca parinti pe " + model.NumeTata + " si " + model.NumeMama + " in grupa: " + model.Grupa+". "+ Environment.NewLine + "Locul de munca al parintilor: " + model.LocDeMunca;
                mm.IsBodyHtml = true;
                mm.Priority = MailPriority.High;


                //atasam CN copil
                if (model.CopieCN.Length > 0)
                {
                    string fileNameCN = Path.GetFileName(model.CopieCN.FileName);
                    Attachment file1 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCN, MediaTypeNames.Application.Octet);
                    mm.Attachments.Add(file1);
                    //file1.Dispose();
                    //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCN, MediaTypeNames.Application.Octet));
                }
                //atasam CI tata
                if (model.CopieCIT.Length > 0)
                {
                    string fileNameCIT = Path.GetFileName(model.CopieCIT.FileName);
                    Attachment file2 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCIT, MediaTypeNames.Application.Octet);
                    mm.Attachments.Add(file2);
                    //fie2.Dispose();
                    //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCIT, MediaTypeNames.Application.Octet));
                }
                //atasam CI mama
                if (model.CopieCIM.Length > 0)
                {
                    string fileNameCIM = Path.GetFileName(model.CopieCIM.FileName);
                    Attachment file3 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCIM, MediaTypeNames.Application.Octet);
                    mm.Attachments.Add(file3);
                    //file3.Dispose();
                    //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCIM, MediaTypeNames.Application.Octet));
                }

                //here we try another approach for multi attach
                //first we create a list of files
                List<string> AttachList = new List<string>();
                AttachList.Clear();
                if (model.CopieCN.Length > 0)
                {
                    AttachList.Add(Path.GetFileName(model.CopieCN.FileName));
                }
                if (model.CopieCIT.Length > 0)
                {
                    AttachList.Add(Path.GetFileName(model.CopieCIT.FileName));
                }
                if (model.CopieCIM.Length > 0)
                {
                    AttachList.Add(Path.GetFileName(model.CopieCIM.FileName));
                }
                //

                foreach (var filepath in AttachList) //this is commented in real life
                {
                    var attachment = new Attachment(filepath);   // here you can attach a file as a mail attachment  
                    mm.Attachments.Add(attachment);
                }
                //

                using (SmtpClient smtp = new SmtpClient())
                {
                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    NetworkCredential NetworkCred = new NetworkCredential("sender.email@gmail.com", "@Password@");
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = 587;

                    try {
                        smtp.Send(mm);
                    ViewBag.Message = "Mesaj trimis cu succes."; }
                    catch (Exception ex) {
                        ViewBag.Message = ("S-a produs o eroare: {0}", ex.ToString());
                    }
                    finally
                    {
                        //Clear all the form's fields
                    }


            }
            }

            return View();
            //return new RedirectResult("https://www.some-site.com");
        }

Here comes the error:

/*Error rised*/

/*line 105 is: smtp.Send(mm); */

(S-a produs o eroare: {0}, System.Net.Mail.SmtpException: Failure sending mail. ---> System.InvalidOperationException: The inner stream position has changed unexpectedly. at Microsoft.AspNetCore.Http.ReferenceReadStream.VerifyPosition() at Microsoft.AspNetCore.Http.ReferenceReadStream.Read(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Mime.MimePart.Send(BaseWriter writer, Boolean allowUnicode) at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer, Boolean allowUnicode) at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope, Boolean allowUnicode) at System.Net.Mail.SmtpClient.Send(MailMessage message) --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send(MailMessage message) at Inscrieri.Inima.Controllers.HomeController.Index(EmailModel model) in C:\Users\laurentiu\source\repos\Inscrieri.Inima\Inscrieri.Inima\Controllers\HomeController.cs:line 105)

Any hint will be appreciated.

Regards

ASP.net core and graphQL

$
0
0

I have build an asp.net core project which get Rest API calls and return data.

now I added a GraphQL option as well, and I have some issue not clear :

1. when I run the project and go to http://localhost:61171/ui/playground 

In my Query and Type class I put a breakpoint which I see something is calling this all the time over and and over.

2. in my Type class I tried to set a Field which returns a List of Data

a. I get an error :

System.ArgumentException: 'The GraphQL type for Field: 'Items' on parent type: 'GetReportType' could not be derived implicitly.

how should i set this field? is it possible to give the client to query only specific properties :

public List<Report> Items { get; set; }


public class Report
    {
        public string RefID{ get; set; }
        public DateTime CreateTime { get; set; }
        public string Text { get; set; }
}

==>I solved this issue #2 by define: Field<ListGraphType<ReportType>>("items");

3. how can i read a KEY which sent in the HEADER and called "MYKEY"

==> this is (#3) solved based on this https://stackoverflow.com/a/53214052/9698435

in the Query class?

thanks for the help


Problem uploading with MS Edge

$
0
0

First please see this post: https://forums.asp.net/t/2166962.aspx

The code in that post works perfect in Firefox and Chrome.  However it does not in Edge.

For example, if the image is located at C:\Users\jimwin7a\Pictures\ann.jpg

Firefox works and just ann.jpg is stored for file name, but Edge stores this for file name C:\Users\jimwin7a\Pictures\ann.jpg

Actually something like ann37.jpg (see the code that works in other post).  And image isn't uploaded to server, it put in same folder you get the file from.

Why in the World wouldn't Edge handle proper file uploads?

Again code here https://forums.asp.net/t/2166962.aspx works perfect in the other two mentioned browsers.

So any help would be nice.

Data annotation inside MVC6 web grid

$
0
0

I have added the following model class inside my asp.net MVC core web application 3.1:-

[ModelMetadataType(typeof(Submission_Validation))]
    public partial class Submission
    {


    }

and the following Submission_Validation class:-

public class Submission_Validation
    {

[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "{0:dd MMMM yyyy hh:mm:ss tt}")]
public DateTime Created { get; set; }
    }

now if i show the Created field using @Html.DisplayFor(model => model.Created) the date will have the correct format as specified inside the data annotation, but if i render the value inside the MVC-6-Grid (https://mvc6-grid.azurewebsites.net/) as follow:-

@(Html
    .Grid(Model)
    .Build(columns =>
    {
columns.Add(model => model.Created).Titled("Created")
})
    .Using(GridFilterMode.Header)
    .Empty("No data found")
    .Filterable()
    .Sortable()
    .Pageable(pager =>
    {

        pager.RowsPerPage = 250;
    })

the date will ignore the data annotation specified. any idea how i can fix this?

Binding to a complex ViewModel

$
0
0

I have a model class called linksmvccore.  It's just a link number with IDs pointing to data in 2 other tables

    [Table("linksmvccore")]
    public partial class Linksmvccore
    {
        [Key]
        [Column(TypeName = "int(11)")]
        public int LinkNumber { get; set; }
        [Column("BagID", TypeName = "int(11)")]
        public int? BagId { get; set; }
        [Column("PersonID", TypeName = "int(11)")]
        public int? PersonId { get; set; }
    }

I also have a compound ViewModel

        public class AllLinkViewModel
        {
            public Bagsmvc Bag { get; set; }
            public Peoplemvc Person { get; set; }
            public Linksmvccore Link { get; set; }
            public List<Peoplemvc> People { get; set; }
            public List<Bagsmvc> Bags{ get; set; }
            public List<Linksmvccore> Links { get; set; }
}

And here's the edit view

@model BagContext.AllLinkViewModel

@{
    ViewData["Title"] = "Edit";
}<h1>Edit</h1><div class="row"><div class="col-md-4"><form asp-action="Edit"><input type="hidden" asp-for="Link.LinkNumber" /><div class="form-group"><label asp-for="Link.BagId" class="control-label"></label><input asp-for="Link.BagId" class="form-control" /></div><div class="form-group"><label asp-for="Link.PersonId" class="control-label"></label><input asp-for="Link.PersonId" class="form-control" /></div><input type="submit" value="Save" asp-route-everything="@Model" class="btn btn-primary" /></div></form></div></div>

I can pass the model to the Edit controller successfully like this

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, AllLinkViewModel alvm) {

...

}

But I am unable to prevent overbinding

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id,      
               [Bind("Link.LinkNumber,BagId,Link_PersonId")] AllLinkViewModel alvm)

I've tried 3 different ways of Binding but none of them will bind with the model.  How can I prevent overbinding here?

Web.Api core sudden increase of memory

$
0
0

I have a web.api in .net core 3.1 that continually receives byte array data. I have noticed that after a dozen of calls, the memory suddenly increases with +100Mb.

As you can see in the GIF, the memory increases steadily as the calls are being handled. And then at 155Mb, the memory increases to 296Mb.

I have created a repo: https://github.com/puppetSpace/MemoryIssue This contains a client project, that calls the API continually. And the web.api project, that gets the byte array from the body and waits 500ms (simulate work). I just want to know a couple of things:

  • Is someone else also getting this result?
  • Is this normal behavior? like it's reserving memory? Or it's just because of debbuging?

I tried to use a profiler, but I can't figure out what causes the sudden increase.

I also asked this on stack overflow, but I think I'm gonna get a better answer here: https://stackoverflow.com/questions/62138833/net-core-web-api-sudden-memory-peak-after-dozen-of-calls/62144292#62144292

tooling issue - version conflict detected for microsoft.extensions.configuration

$
0
0

"Install/reference microsoft.extensions.configuration 3.1.4 directly to project UserNameAPI to resolve this issue"

Points to file UserNameAPI.csproj

<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup><TargetFramework>netcoreapp2.2</TargetFramework><AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.AspNetCore.App" /><PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.4" /><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" /><PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4"><PrivateAssets>all</PrivateAssets><IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets></PackageReference><PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.4" /></ItemGroup><ItemGroup><ProjectReference Include="..\UserNameLibrary\UserNameLibrary.csproj" /></ItemGroup></Project>

When I do that through the package manager it fails:

Severity	Code	Description	Project	File	Line	Suppression State
Error		Package restore failed. Rolling back package changes for 'UserNameAPI'.				
Error	NU1107	Version conflict detected for Microsoft.Extensions.Configuration. Install/reference Microsoft.Extensions.Configuration 3.1.4 directly to project UserNameAPI to resolve this issue. 
 UserNameAPI -> UserNameLibrary -> Microsoft.Extensions.Http 3.1.4 -> Microsoft.Extensions.Logging 3.1.4 -> Microsoft.Extensions.Configuration.Binder 3.1.4 -> Microsoft.Extensions.Configuration (>= 3.1.4) 
 UserNameAPI -> Microsoft.AspNetCore.App 2.2.0 -> Microsoft.Extensions.Configuration (>= 2.2.0 && < 2.3.0).	UserNameAPI	C:\Users\Robert\source\Repos\SchoolNew\UserNameAPI\UserNameAPI.csproj	1	
Error	NU1107	Version conflict detected for Microsoft.Extensions.Configuration. Install/reference Microsoft.Extensions.Configuration 3.1.4 directly to project UserNameAPI to resolve this issue. 
 UserNameAPI -> UserNameLibrary -> Microsoft.Extensions.Http 3.1.4 -> Microsoft.Extensions.Logging 3.1.4 -> Microsoft.Extensions.Configuration.Binder 3.1.4 -> Microsoft.Extensions.Configuration (>= 3.1.4) 
 UserNameAPI -> Microsoft.AspNetCore.App 2.2.0 -> Microsoft.Extensions.Configuration (>= 2.2.0 && < 2.3.0).	UserNameAPI	C:\Users\Robert\source\Repos\SchoolNew\UserNameAPI\UserNameAPI.csproj	1	

How to proceed from here?

How can i include more than one include in the query

$
0
0

I have the following model

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

        [Required]
        [StringLength(10,MinimumLength =3, ErrorMessage ="ISBN must be between 3 and 10 characters")]
        public string Isbn { get; set; }

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

        public DateTime? DatePublished { get; set; }

        [ForeignKey("CategoryId")]
        public int CategoryId { get; set; }
        public Category Category { get; set; }

        [ForeignKey("AuthorId")]
        public int AuthorId { get; set; }
        public Author Author { get; set; }
        public  ICollection<Review> Reviews { get; set; }

In my sql how can I include  <Category > object along with the given sql. Please help

 public ICollection<Book> GetBooks()
        {
            return _db.Books.Include(a => a.Author).OrderBy(b => b.Title).ToList();
        }

Route to a specific action explicitly from middleware

$
0
0

I'm still trying to migrate my transparent login router to ASP.NET Core 3 with the new endpoint routing. My current approach is to insert a middleware before the routing happens. When this middleware detects that the user is not logged in, the login action must be invoked instead of whatever the URL requested. When the user has logged in, the same original URL will then serve the requested page. Here's my middleware in the Startup.Configure method:

...
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.Use(async (context, next) =>
{
	if (!context.User.Claims.Any())
	{
		var routeData = context.GetRouteData();
		routeData.Values["controller"] = "Account";
		routeData.Values["action"] = "Login";
	}
	// Call the next delegate/middleware in the pipeline
	await next();
});

app.UseEndpoints(endpoints =>
...

It correctly determines the logged in state but then can't change the routing. The shown code will serve the Account/Loginview, but the code still executes the Home/Index action. This doesn't match so I probably destroyed the routing data with this.

How can I force the Account/Login action and view to be called here from the middleware, without changing the URL (no redirect allowed)?


CORS Policy - driving me insane

$
0
0

Hey everyone.  

I'm learning .NET Core (currently using version 3.0.1, and ASPNETCORE_ENVIRONMENT is currently in development mode) for development and have built a project that uses the framework for a WebAPI backend, and Angular for the frontend.  Right now I'm running into an issue where no matter how I setup my CORS options, I constantly throw the following error when an API return event forwards the user to a new webpage.  

Right now, I have have method in my API that allows a user to create a new password (using Microsoft Identity) when they click the Forgot Password link in the email they receive.  When the click submit the password is changed and if successful, they are forwarded to the password changed successfully page. Here is that method from the API: 

        [HttpPost("ResetPassword")]
        public async Task<IActionResult> ResetPassword(PasswordResetDto passwordResetDto)
        {
            if (ModelState.IsValid)
            {
                var result = await _resetPasswordRepository.ResetPasswordAsync(passwordResetDto);
                if (result != null)
                    return BadRequest("Invalid details");
            }
            return Redirect($"{_configuration["ViewUrl"]}/#/passwordchanged");
        }

When the return Redirect is hit, the browser throws the following error and no redirect occurs: 

Access to XMLHttpRequest at 'http://localhost:5000/api/auth/forgotpassword' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In my startup.cs file I have the following entered (see the highlighted lines): 

public void ConfigureServices(IServiceCollection services)
        {
            // Add Microsoft Identity Services to the services method
            IdentityBuilder builder = services.AddIdentityCore<User>(opt => 
            {
                // Add weak password ability
                opt.Password.RequireDigit = false;
                opt.Password.RequiredLength = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase = false;
                // opt.SignIn.RequireConfirmedEmail = true;
            }).AddDefaultTokenProviders();

            

            // Add the DbContext method to services so it can be called from other aread of the webapp, and call the database connection string.
            builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
            builder.AddEntityFrameworkStores<DataContext>();
            builder.AddRoleValidator<RoleValidator<Role>>();
            builder.AddRoleManager<RoleManager<Role>>();
            builder.AddSignInManager<SignInManager<User>>();

            // Add the JWT Token Service
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)  // Add authentication as a service.  Tell DotNet Core the type of authentication
                .AddJwtBearer(options => {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                            .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });

            // Add roles based authorization policies
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireGlobalAdminRole", policy => policy.RequireRole("GlobalAdmin"));
                options.AddPolicy("RequireClientAdminRole", policy => policy.RequireRole("GlobalAdmin", "ClientAdmin"));
                options.AddPolicy("RequireLocationAdminRole", policy => policy.RequireRole("GlobalAdmin", "ClientAdmin", "LocationAdmin"));
                options.AddPolicy("RequireReportsOnlyRole", policy => policy.RequireRole("GlobalAdmin", "ClientAdmin", "LocationAdmin", "ReportsOnly"));
            });

            // Add all other services
            services.AddDbContext<DataContext>(x => x.UseSqlite
                (Configuration.GetConnectionString("DefaultConnection")));          // Make the DbContext service available to the rest of the application
            services.AddControllers(options => 
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();

                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddNewtonsoftJson();                                                   // Make the Controllers service available to the rest of the application
            services.AddCors();                                                     // Make the CORS policy service available to the rest of the application
            services.AddAutoMapper(typeof(ClientRepository).Assembly);              // Make AutoMapper service available to the rest of the application
            services.AddScoped<IClientRepository, ClientRepository>();              // Make the client repository service available to the rest of the application
            services.AddScoped<ILocationsRepository, LocationsRepository>();        // Make the locations repository service available to the rest of the application
            services.AddScoped<IOrganizationRepository, OrganizationsRepository>(); // Make the Organizations repository service available to the rest of the application
            services.AddTransient<IMailRepository, MailRepository>();               // Mail service from SendGrid
            services.AddScoped<IResetPasswordRepository, ResetPasswordRepository>();// Make the reset password service available to the rest of the application
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // This is the middleware that intracts with the app and the API.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // If in production mode, pass any errors so they can be read
                app.UseExceptionHandler(builder => {
                    builder.Run(async context => {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get<IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }

            // app.UseHttpsRedirection();

            // Routes all requests to the appropriate location 
            app.UseRouting();

            // Defines a CORS policyModify the http headers to prevent the 'Access-Control-Allow-Origin' error from blocking the API.  
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            // Controls authorization for logging users in and determines what areas they have access to
            app.UseAuthentication();
            app.UseAuthorization();

            // As the web applications starts up, this maps the controller endpoints into the web application so the web application knows how to route the requests.
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

To add context, the data is being passed to the API using from my angular Auth service using the following: 

  resetChangePassword(email: string, token: string, newPassword: string, confirmPassword: string) {
    return this.http.post(`${this.baseUrl}` + `resetpassword`, { newPassword, confirmPassword, token, email });
  }

Any ideas on what I am doing wrong here?  I have also tried reconfiguring the CORS policies using different methods with zero success such as:

ConfigureServices:

services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
); });

Configure:

app.UseCors("CorsPolicy");

I just cant seem to get around this.  Any insight will be greatly appreciated. 

Fake dll support in .net core

$
0
0

Hi Team,

I am doing migration asp.net project 4.5 framework to asp.net core 3.1

Can you please let me know fake dll is supported in .net core while migrating i can see fake dll is used in many place in 4.5 frameworks.

any suggestion and help will be highly appreciated on how to proceed further on this.
Regards

How to get connection from startup to static class Data access?

$
0
0

I work on asp.net core 2.2 vs2017 app I face issue I cannot get connection string from start up to static Data access class 

class CZConnection
  public class CZConnection
    {


        public string DashboardConnection { get; set; }

    
    }
StartUp.cs
services.Configure<CZConnection>(DBConnection =>
            {
                DBConnection.DashboardConnection = Configuration.GetConnectionString("DashBoardSQLConnection");



            });

public static partial class DataAccess
{
  static SqlConnection InitializeConnection()
    {
     
          
               
                return new SqlConnection(here I need to get connection string of DBConnection.DashboardConnection);
             


        }
        return new SqlConnection();

 
}

What happen if someone do not accept the GDPR alert inside asp.net mvc core 3.1

$
0
0

I am working on an Asp.net MVC core 3.1 registration web site for the US market, where the users enter his/her mobile number >> and on the next screen they enter their info to register with us. and we want to track the users who enter their mobile numberx but do not register.and since we are tracking the users' actions, so i added the GDPR alert by following the steps mentioned on this link @ https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-3.1.

but i am not sure what i need to do then?. I have these 3 questions:-

Question1) If someone accept the alert, then this mean that we can track if he did not complete the registration?

Question2) How i can know that the user accept or did not accept the GDPR alert inside my code?

Question3) If the user did not accept the GDPR alert, then is it still fine to track if the user enter his/her mobile number but did not register?

Thanks

Field not rendering across 3 table relationship

$
0
0

Hi So I am using ASP.NET Core 2.2 with EF Core with SQL Server DB. I got a database that looks like this. So I have 3 tables in SQL Server. tblJobs, tblResults and tblProblems and others I omitted as they are not part of the problem.

Entity Relationship Diagram and gif demo of problem

I am attempting to read related data across these three tables. I am using Eager Loading to read the model field "Job.JobTitle" in the "ProblemsController.Index" method with this tutorial. https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/read-related-data?view=aspnetcore-2.2

I decided to manually insert in a query window into Result table the JobID matching the JobTitle I wanted with the ProblemID. It has now rendered the correct JobTitle in the Problem Index view record which is the value of "Pitcher". But that's only because I manually inserted it in tblResult which doesn't really help the end user. I'm wondering what's a way of them getting past that manual insertion.

Here is the my TeamContext class.

using Pitcher.Models;
using Microsoft.EntityFrameworkCore;
using Pitcher.Models.TeamViewModels;

namespace Pitcher.Data
{
    public class TeamContext : DbContext
    {
        public TeamContext(DbContextOptions<TeamContext> options) : base(options)
        {
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Registration> Registrations {get;set;}
        public DbSet<Job> Jobs {get;set;}     

        public DbSet<Problem> Problems { get; set; }   

        public DbSet<Result> Results {get;set;}
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().ToTable("tblUser");
            modelBuilder.Entity<Registration>().ToTable("tblRegistration");
            modelBuilder.Entity<Job>().ToTable("tblJob");
            modelBuilder.Entity<Problem>().ToTable("tblProblem");
            modelBuilder.Entity<Chat>().ToTable("tblChat");
            modelBuilder.Entity<Result>().ToTable("tblResult");

            modelBuilder.Entity<Result>()
                .HasKey(bc => new { bc.JobID, bc.ProblemID });
            modelBuilder.Entity<Result>()
                .HasOne(bc => bc.Job)
                .WithMany(b => b.Results)
                .HasForeignKey(bc => bc.JobID);
            modelBuilder.Entity<Result>()
                .HasOne(bc => bc.Problem)
                .WithMany(c => c.Result)
                .HasForeignKey(bc => bc.ProblemID);
        }        
    }
}

Here are the 3 models.

Job model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace Pitcher.Models
{
    public class Job
    {        
        
        public int ID { get; set; }

        [Required]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Job Title must be bettween 3 to 20 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Job Title")]
        [Column("JobTitle")]
        public string JobTitle { get; set; }

        [StringLength(200, MinimumLength = 3, ErrorMessage = "Job Description must be bettween 200 to 3 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Description")]
        [Column("JobDescription")]
        public string JobDescription { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = " Start Date")]
        [Column("JobStartDate")]
        public DateTime JobStartDate {get;set;}

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Deadline Date")]
        [Column("JobDeadlineDate")]
        public DateTime JobDeadline {get;set;}

        [Display(Name = "Job Is Complete?")]
        [Column("JobIsComplete")]
        public bool JobIsComplete{get;set;}

        public ICollection<Registration> Registrations {get;set;}

        public ICollection<Result> Results {get;set;}
    }
}

Result model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Pitcher.Models
{
    public class Result
    {        
        public int JobID {get;set;}
        
        public int ProblemID {get;set;}
        public Job Job {get;set;}
        public Problem Problem {get;set;}

    }
}

Problem model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace Pitcher.Models
{
    public class Problem
    {
        public int ID {get;set;}
        
        [Required]
        [StringLength(180, MinimumLength = 2, ErrorMessage = "Problem Title must be bettween 2 to 20 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Problem Title")]
        [Column("ProblemTitle")]
        public string ProblemTitle {get;set;}

        [Required]
        [StringLength(int.MaxValue, MinimumLength = 5, ErrorMessage = "Problem Title must be at least 5 characters.")]
        [DataType(DataType.Text)]
        [Display(Name = "Problem Description")]
        [Column("ProblemDescription")]
        public string ProblemDescription {get;set;}

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = " Problem Start Date")]
        [Column("ProblemStartDate")]
        public DateTime ProblemStartDate {get;set;}

        [DataType(DataType.Upload)]
        [Display(Name = " Upload file")]
        [Column("ProblemFileAttachments")]
        public string ProblemFileAttachments {get;set;}

        [Required]
        [Display(Name = "Problem Severity")] 
        [Range(1,5, ErrorMessage
             = "Problem Severity value for {0} must be between {1} and {2}.")]       
        [Column("ProblemSeverity")]
        public int ProblemSeverity {get;set;}

        [Display(Name = "Problem Complete")]        
        [Column("ProblemComplete")]        
        public bool ProblemComplete {get;set;}
        public ICollection<Result> Result {get;set;}

        public ICollection<Chat> Chat {get;set;}
    }
}

Here are the 2 Controllers I'm using with their Index methods only.

Job Index controller method:

        public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["JobTitleSortParm"] = sortOrder == "JobStartDate" ? "JobTitle_desc" : "JobStartDate";
            ViewData["JobStartDateSortParm"] = sortOrder == "JobStartDate" ? "JobStart_date_desc" : "JobStartDate";
            ViewData["JobDeadlineDateSortParm"] = sortOrder == "JobDeadlineDate" ? "JobDeadline_date_desc" : "JobDeadlineDate";
            ViewData["CurrentFilter"] = searchString;
            var jobs = from j in _context.Jobs
                        select j;

            if (searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }


            if (!String.IsNullOrEmpty(searchString))
            {
                jobs = jobs.Where(j => j.JobTitle.Contains(searchString)
                                    || j.JobDescription.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "JobTitle_desc":
                    jobs = jobs.OrderByDescending(j => j.JobTitle);
                    break;
                case "JobStartDate":
                    jobs = jobs.OrderBy(j => j.JobStartDate);
                    break;
                case "JobStart_date_desc":
                    jobs = jobs.OrderByDescending(j => j.JobStartDate);
                    break;
                case "JobDeadline_date_desc":
                    jobs = jobs.OrderByDescending(j => j.JobDeadline);
                    break;
                case "JobDeadlineDate":
                    jobs = jobs.OrderBy(j => j.JobDeadline);
                    break;
                //By default JobTitle is in ascending order when entity is loaded. 
                default:
                    jobs = jobs.OrderBy(j => j.JobTitle);
                    break;                    
            } 

            int pageSize = 20;
            return View(await PaginatedList<Job>.CreateAsync(jobs.AsNoTracking(), pageNumber ?? 1, pageSize));
        }

Problem Index controller method:

public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["ProblemIDSortParm"]  = sortOrder == "ProblemID" ? "ProblemID_desc" : "ProblemID";
            ViewData["ProblemTitleSortParm"] = sortOrder == "ProblemTitle" ? "ProblemTitle_desc" : "ProblemTitle";
            ViewData["ProblemStartDateSortParm"] = sortOrder == "ProblemStartDate" ? "ProblemStartDate_desc" : "ProblemStartDate";
            ViewData["ProblemSeveritySortParm"] = sortOrder == "ProblemSeverity" ? "ProblemSeverity_desc" : "ProblemSeverity";
            ViewData["ProblemCompleteSortParm"] = sortOrder == "ProblemComplete" ? "ProblemComplete_desc" : "ProblemComplete";          
            ViewData["CurrentFilter"] = searchString;
            //READ RELATED DATA HERE
            var problems = from p in _context.Problems 
                            .Include(p => p.Result)
                                .ThenInclude(j => j.Job)                                                     
                                select p;
            //END OF READ RELATED DATA
            if(searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            if(!String.IsNullOrEmpty(searchString))
            {
                problems = problems.Where(p => p.ProblemTitle.Contains(searchString)
                                            || p.ProblemDescription.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "ProblemID_desc":
                    problems = problems.OrderByDescending(p => p.ID);
                    break;
                case "ProblemTitle_desc":
                    problems = problems.OrderByDescending(p => p.ProblemTitle);
                    break;
                case "ProblemTitle":
                    problems = problems.OrderBy(p => p.ProblemTitle);
                    break;
                case "ProblemStartDate":
                    problems = problems.OrderBy(p => p.ProblemStartDate);                    
                    break;
                case "ProblemStartDate_desc":
                    problems = problems.OrderByDescending(p => p.ProblemStartDate);                    
                    break;
                case "ProblemSeverity":
                    problems = problems.OrderBy(p => p.ProblemSeverity);
                    break;
                case "ProblemSeverity_desc":
                    problems = problems.OrderByDescending(p => p.ProblemSeverity);
                    break;   
                case "ProblemComplete":
                    problems = problems.OrderBy(p => p.ProblemComplete);
                    break;
                case "ProblemComplete_desc":
                    problems = problems.OrderByDescending(p => p.ProblemComplete);
                    break; 
                default:
                    problems = problems.OrderBy(p => p.ID);
                    break;                 
            }

            int pageSize = 20;            
            return View(await PaginatedList<Problem>.CreateAsync(problems.AsNoTracking(), pageNumber ?? 1, pageSize));
        }

And the Index view for Problem:

@model PaginatedList<Pitcher.Models.Problem>

@{
    ViewData["Title"] = "Problems";
}<h1>Problems</h1><p><a asp-action="Create">Create New</a></p>
 @*COPY AND PASTE THIS TAG HELPER METHOD TEXTBOX CUSTOMIZATION INTO OTHER VIEWS TO ENABLE SEARCHING.*@<form asp-action="Index" method="get"><div class="form-actions no-color"><p>
            Find by name: <input type="text" name="SearchString" value="@ViewData["currentFilter"]" /><input type="submit" value="Search" button type="button" class="btn btn-primary" /> |<a asp-action="Index">Back to Full List </a></p></div></form><table class="table table-hover"><thead><tr><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemIDSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem ID</a></th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemTitleSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem Title</a></th><th>
                Description</th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemStartDateSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">Problem Start Date</a></th><th>
                Problem File Attachments</th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemSeveritySortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">ProblemSeverity</a></th><th><a asp-action="Index" asp-route-sortOrder="@ViewData["ProblemCompleteSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">ProblemComplete</a></th><th>
                Job Title</th><th></th></tr></thead><tbody>
@foreach (var item in Model) {<tr><td>
                @Html.DisplayFor(modelItem => item.ID)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemTitle)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemDescription)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemStartDate)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemFileAttachments)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemSeverity)</td><td>
                @Html.DisplayFor(modelItem => item.ProblemComplete)</td><td>
                @foreach (var title in item.Result)
                {
                    @Html.DisplayFor(modelItem => title.Job.JobTitle)<br />
                }</td><td><a asp-action="Edit" asp-route-id="@item.ID" button type="button" class="btn btn-primary btn-block" >Edit</a> <a asp-action="Details" asp-route-id="@item.ID" button type="button" class="btn btn-info btn-block">Details</a> <a asp-action="Delete" asp-route-id="@item.ID" button type="button" class="btn btn-primary btn-block">Delete</a></td></tr>}</tbody></table>
@{
    var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
    var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}<a asp-action="Index"
   asp-route-sortOrder="@ViewData["CurrentSort"]"
   asp-route-pageNumber="@(Model.PageIndex - 1)"
   asp-route-currentFilter="@ViewData["CurrentFilter"]"
   class="btn btn-secondary @prevDisabled"
   button type="button">
    Previous</a><a asp-action="Index"
   asp-route-sortOrder="@ViewData["CurrentSort"]"
   asp-route-pageNumber="@(Model.PageIndex + 1)"
   asp-route-currentFilter="@ViewData["CurrentFilter"]"
   class="btn btn-secondary @nextDisabled"
   button type="button">   
    Next</a>

Kind regards,

Jordan Nash

Viewing all 9386 articles
Browse latest View live


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