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

How to display a picture, checkbox, combobox in a table?

$
0
0

1. How to display a picture, checkbox, combobox for the current model in the table?
2. How to make the model correctly in order to display a picture, checkbox, combobox in the table?
 
Currently, I get the result, which is shown in the picture.
 
ASP.NET Core 3.1

<div>Company.cs</div> <div>
public class Company    {        public int Id { get; set; }                public string Picture { get; set; }        public string Name { get; set; }        public string Description{ get; set; }        public bool Status { get; set; }                  public Status2 Status2Value { get; set; }                     public class Status2        {            public int ID { get; set; }            public string Status { get; set; }        }    }
</div> <div> </div> <div>HomeController.cs</div> <div>
public class HomeController : Controller    {        public IActionResult Index()        {                        List<Company> companies_List = new List<Company>();              companies_List = MockCompanyData.CompanyList_prop;             List<Company.Status2> status2_List = new List<Company.Status2>();            status2_List = MockCompanyData.CompanyStatus2_prop;             IndexVM indexVM = new IndexVM { Companies = companies_List, companyStatus2 = status2_List };             return View(indexVM);                 }           }
</div> <div> </div> <div>IndexVM.cs</div> <div>
public class IndexVM    {        public IEnumerable<Company> Companies { get; set; }        public IEnumerable<Company.Status2> companyStatus2 { get; set; }       }
</div> <div> </div> <div>MockCompanyData.cs</div> <div>
static class MockCompanyData    {                static string mainPathForImg = @"";         static List<Company.Status2> companyStatus2List = new List<Company.Status2>        {            new Company.Status2 {ID=1, Status = ""},            new Company.Status2 {ID=2, Status = "Yes"},            new Company.Status2 {ID=3, Status = "No"}        };         static List<Company> companyList = new List<Company>        {            new Company {Id = 1, Picture = mainPathForImg + @"~/img/number_1_blue.png", Name ="Name_Company_1", Description ="Description_1", Status = true, Status2Value = companyStatus2List[0]},            new Company {Id = 2, Picture = mainPathForImg + @"~/img/number_2_blue.png", Name ="Name_Company_2", Description ="Description_2", Status = false, Status2Value = companyStatus2List[1]},            new Company {Id = 3, Picture = mainPathForImg + @"~/img/number_3_blue.png", Name ="Name_Company_3", Description ="Description_3", Status = true, Status2Value =companyStatus2List[0]}                   };         public static List<Company> CompanyList_prop        {            get            {                return companyList;            }            set            {                companyList = value;            }        }         public static List<Company.Status2> CompanyStatus2_prop        {            get            {                return companyStatus2List;            }            set            {                companyStatus2List = value;            }        }     }
</div> <div> </div> <div>Index.cshtml</div> <div>
@using WebApplCore.Core.ViewModels;
@using WebApplCore.Models; 
@model IndexVM; 
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <head>    <link href="~/css/bootstrap.min.css" rel="stylesheet" type="text/css" /></head> <body>    <div class="container">                <table class="table table-sm table-hover table-striped">            <thead class="thead-dark">                                @{var headerMetadata = Model.Companies.FirstOrDefault();}                <tr>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Id)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Picture)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Name)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Description)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Status)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Status2Value)                    </th>                    <th></th>                </tr>            </thead>            <tbody>                @foreach (Company item in Model.Companies)                {                    <tr>                        <td>                            @Html.DisplayFor(modelItem => item.Id)                            @*@item.Id*@                        </td>                        <td>                                                        <img src="@Html.DisplayFor(modelItem => item.Picture)" class="rounded-circle" asp-append-version="true" alt="No Picture">                        </td>                        <td>                            @Html.DisplayFor(modelItem => item.Name)                        </td>                        <td>                            @Html.DisplayFor(modelItem => item.Description)                        </td>                        <td>                            <input type="checkbox" value=@Html.DisplayFor(modelItem => item.Status)>                                                    </td>                        <td>                            <select name="companyId" class="form-control">                                @foreach (Company.Status2 status2 in Model.companyStatus2)                                {                                    <option value="@status2.ID">@Html.DisplayFor(modelItem => status2.Status)</option>                                }                            </select>                         </td>                        <td>                            <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |                            <a asp-action="Details" asp-route-id="@item.Id">Details</a> |                            <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>                        </td>                    </tr>                }            </tbody>        </table>    </div></body>
</div> <div></div> <div></div>

migrate 3rd party library in .net core

$
0
0

Hi team,

I am doing migration of asp.net project to .net core 3.1

how to migrate 3rd party library is it possible any suggestion would be helpful

regards

How to place an ASP.NET Core project in dotnetfiddle.net?

$
0
0

I have a project.
 
How to put it in `dotnetfiddle.net`?
Or which online compiler to use for ASP.NET Core?
 
I try to post it, but I get errors.
I try to connect NuGet, but this also does not lead to a result.

Project - https://dotnetfiddle.net/HOG4bJ

<div>Company.cs</div> <div>

public class Company    {        public int Id { get; set; }                public string Picture { get; set; }        public string Name { get; set; }        public string Description{ get; set; }        public bool Status { get; set; }                  public Status2 Status2Value { get; set; }                     public class Status2        {            public int ID { get; set; }            public string Status { get; set; }        }    }

</div> <div> </div> <div>HomeController.cs</div> <div>

public class HomeController : Controller    {        public IActionResult Index()        {                        List<Company> companies_List = new List<Company>();              companies_List = MockCompanyData.CompanyList_prop;             List<Company.Status2> status2_List = new List<Company.Status2>();            status2_List = MockCompanyData.CompanyStatus2_prop;             IndexVM indexVM = new IndexVM { Companies = companies_List, companyStatus2 = status2_List };             return View(indexVM);                 }           }

</div> <div> </div> <div>IndexVM.cs</div> <div>

public class IndexVM    {        public IEnumerable<Company> Companies { get; set; }        public IEnumerable<Company.Status2> companyStatus2 { get; set; }       }

</div> <div> </div> <div>MockCompanyData.cs</div> <div>

static class MockCompanyData    {                static string mainPathForImg = @"";         static List<Company.Status2> companyStatus2List = new List<Company.Status2>        {            new Company.Status2 {ID=1, Status = ""},            new Company.Status2 {ID=2, Status = "Yes"},            new Company.Status2 {ID=3, Status = "No"}        };         static List<Company> companyList = new List<Company>        {            new Company {Id = 1, Picture = mainPathForImg + @"~/img/number_1_blue.png", Name ="Name_Company_1", Description ="Description_1", Status = true, Status2Value = companyStatus2List[0]},            new Company {Id = 2, Picture = mainPathForImg + @"~/img/number_2_blue.png", Name ="Name_Company_2", Description ="Description_2", Status = false, Status2Value = companyStatus2List[1]},            new Company {Id = 3, Picture = mainPathForImg + @"~/img/number_3_blue.png", Name ="Name_Company_3", Description ="Description_3", Status = true, Status2Value =companyStatus2List[0]}                   };         public static List<Company> CompanyList_prop        {            get            {                return companyList;            }            set            {                companyList = value;            }        }         public static List<Company.Status2> CompanyStatus2_prop        {            get            {                return companyStatus2List;            }            set            {                companyStatus2List = value;            }        }     }

</div> <div> </div> <div>Index.cshtml</div> <div>

@using WebApplCore.Core.ViewModels;
@using WebApplCore.Models; 
@model IndexVM; 
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <head>    <link href="~/css/bootstrap.min.css" rel="stylesheet" type="text/css" /></head> <body>    <div class="container">                <table class="table table-sm table-hover table-striped">            <thead class="thead-dark">                                @{var headerMetadata = Model.Companies.FirstOrDefault();}                <tr>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Id)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Picture)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Name)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Description)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Status)                    </th>                    <th>                        @Html.DisplayNameFor(model => headerMetadata.Status2Value)                    </th>                    <th></th>                </tr>            </thead>            <tbody>                @foreach (Company item in Model.Companies)                {                    <tr>                        <td>                            @Html.DisplayFor(modelItem => item.Id)                            @*@item.Id*@                        </td>                        <td>                                                        <img src="@Html.DisplayFor(modelItem => item.Picture)" class="rounded-circle" asp-append-version="true" alt="No Picture">                        </td>                        <td>                            @Html.DisplayFor(modelItem => item.Name)                        </td>                        <td>                            @Html.DisplayFor(modelItem => item.Description)                        </td>                        <td>                            <input type="checkbox" value=@Html.DisplayFor(modelItem => item.Status)>                                                    </td>                        <td>                            <select name="companyId" class="form-control">                                @foreach (Company.Status2 status2 in Model.companyStatus2)                                {                                    <option value="@status2.ID">@Html.DisplayFor(modelItem => status2.Status)</option>                                }                            </select>                         </td>                        <td>                            <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |                            <a asp-action="Details" asp-route-id="@item.Id">Details</a> |                            <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>                        </td>                    </tr>                }            </tbody>        </table>    </div></body>

</div> <div></div> <div></div>

Do SMTP Servers give notice on email delivery

$
0
0

Dear All,

I am setting up my own mailing infrastructure for bulk mails for my organisation. My system is meant to send email to an smtp server.

But I want to know when emails have been delivered or not. Please how do I know this. What is the secret around this.

Plesae I am not using a specialized platform for this. See it like am setting up the owl mail infrastructure on my end.

I would be configuring a VPS as my mailing server with a mailclient software on it, to send the emails. If I send email to my VPS mailing server how do I know if the mail was delivered or pending.

Best Regards,

Jide Akindejoye

Using a Queueing System for notification Messages. For 100 % Delivery Gauranttee

$
0
0

Dear All,

So I have built an application that handles several kinds of transactions for merchant. I am trying to build a microservice that would give notification to my merchants.

So my requirement is to ensure that messages deliver even if there is network problems. I am suppose to ensure that there is not failure point at any conditions.

So technical requirement involves I ensure that messages are queued so if there is network problems. So I send messages to another services that would be needing it.

I would also send messages to my merchants through a web hook or call back url. Please Queueing system do I use.

Any materials that I can read up on.

Best Regards,

JIde

All users logged out after server change

$
0
0

Dear All,

I have an existing asp.net core 2.1 application that needs to be migrated to a new host.
On my pre-tests every user is logged out after switching the host.
I copied the existing key files (data protection key ring) to the new host, which were already in my filesystem (PersistKeysToFileSystem) but I never set the applicationname (SetApplicationName).
According to that article (https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-2.1 ) the Data Protection system isolates apps from one another based on their content root paths, if no applicationname is set.
The path is different on the new host, so I think that's my problem losing the logins or am I wrong?

I can‘t use the same path, because on the new host (AzureVM) does not allow _ (underscores) in the file path, which are used on the old one.

So, what can I do to keep every user logged in?

ty

How can I bind different blazor webassemby program into one controller?

$
0
0

Hi, I am intending to develop several Blazor web assembly programs.

For example, my website URL is www.microsoft.com

In my first opinion, I am about to bind the URL like this:

app1.microsoft.com

app2.microsoft.com

app3.microsoft.com

However, the provider of my server limits the subdomain counts to 10.

Now I have to change it like this:

www.microsoft.com/app1/

www.microsoft.com/app2/

www.microsoft.com/app3/

Now the problem is I don't want to add all the blazor programs into one project. And also, I don't want to register any other new domain.

How can I achieve this? Thank you.

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

$
0
0

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


How can I generate and use Gmail API to send email from Application for the login confirmation

$
0
0

I want to include the email  confirmation from the user to activate their account in  to the application. Is it possible to generate Gmail API key to send the email . If so, Please can you let me know the steps

Pol

Number format not working!

$
0
0

Hi

In my model metadata i've using this code to format quantity number with n1 :

public partial class DefaultVisitProductDetailsMetadata
{
        [DisplayName("Drug Name")]
        [Required(ErrorMessage = "{0} Required!")]
        public int? ProductID { get; set; }

        [Column(TypeName = "money")]
        [DisplayName("Drug Quantity")]
        [Required(ErrorMessage = "{0} Required!")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N1}")] // Not working
        public decimal? Quantity { get; set; }
}

[ModelMetadataType(typeof(DefaultVisitProductDetailsMetadata))]
public partial class DefaultVisitProductDetails
{

}

But it does not works. Here is my view :

@model DefaultVisitProductDetails<div class="row"><div class="col-md-6"><form id="frmEditPackageDetailItem" asp-action="UpdatePackageDetailItem" method="post"><div asp-validation-summary="All" class="text-danger"></div><input type="hidden" asp-for="DefaultVisitProductDetailRowID" value="@Model.DefaultVisitProductDetailRowID" /><input type="hidden" asp-for="DefaultVisitProductHeaderRowID" value="@Model.DefaultVisitProductHeaderRowID" /><div class="form-group"><label asp-for="ProductID" class="control-label"></label><select asp-for="ProductID" class="form-control" asp-items="@ViewBag.ProductID" value="@Model.ProductID"><option></option></select><span asp-validation-for="ProductID" class="text-danger"></span></div><div class="form-group"><label asp-for="Quantity" class="control-label"></label><input asp-for="Quantity" class="form-control" dir="ltr" value="@Model.Quantity" /><span asp-validation-for="Quantity" class="text-danger"></span></div><div class="form-group"><label asp-for="Description" class="control-label"></label><textarea asp-for="Description" class="form-control" value="@Model.Description"></textarea><span asp-validation-for="Description" class="text-danger"></span></div><div class="modal-footer text-right"><button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button><button type="button" id="btnUpdate" class="btn btn-success" onclick="frmEditPackageDetailItem_onSubmitClick()">Save</button></div></form></div></div>

Can anybody help me what's the problem & how to solve it ?

Thanks in advance

wcf in asp.net core

$
0
0

Hi Team,

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

how to implement wcf in asp.net core can i replace by web api or use gRPC or use microservices or any other suggestion which is better

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

linq-to-twitter Twitter flood get

$
0
0

Hi everyone,

I tried the code below but again it wasn't exactly as I wanted. Only 1 pearl flood is coming.

There are 90 floods. RT ones should not come and should only come flood by call.

as an example I shared the picture. What do I have to do in this situation.

I did but I have Count=0. Why ?

There is registration on this site. How this site does it. Do you know below website.

https://threadreaderapp.com/search?q=HANEDANLAR+MASASININ+YER+ALTI+EGEMENL%C4%B0%C4%9E%C4%B0%3AR%C4%B0O+T%C4%B0NTO

const int MaxSearchEntriesToReturn = 100;
        const int SearchRateLimit = 180;
var myFilter = "-filter:retweets"; string searchTerm = "HANEDANLAR MASASININ YER ALTI EGEMENLİĞİ:RİO TİNTO " + myFilter; // oldest id you already have for this search term ulong sinceID = 1; // used after the first query to track current session ulong maxID; var combinedSearchResults = new List<Status>(); List<Status> searchResponse = await (from search in ctx.Search where search.Type == SearchType.Search && search.Query == searchTerm && search.Count == MaxSearchEntriesToReturn && search.SinceID == sinceID && search.TweetMode == TweetMode.Extended select search.Statuses) .SingleOrDefaultAsync(); if (searchResponse != null) { combinedSearchResults.AddRange(searchResponse); ulong previousMaxID = ulong.MaxValue; do { // one less than the newest id you've just queried maxID = searchResponse.Min(status => status.StatusID) - 1; Debug.Assert(maxID < previousMaxID); previousMaxID = maxID; searchResponse = await (from search in ctx.Search where search.Type == SearchType.Search && search.Query == searchTerm && search.Count == MaxSearchEntriesToReturn && search.MaxID == maxID && search.SinceID == sinceID && search.TweetMode == TweetMode.Extended select search.Statuses) .SingleOrDefaultAsync(); combinedSearchResults.AddRange(searchResponse); } while (searchResponse.Any() && combinedSearchResults.Count < SearchRateLimit); combinedSearchResults.ForEach(tweet => Console.WriteLine("\n User: {0} ({1})\n Tweet: {2}", tweet.User.ScreenNameResponse, tweet.User.UserIDResponse, tweet.Text ?? tweet.FullText) ); } else { Console.WriteLine("No entries found."); } ViewBag.Twet = combinedSearchResults.ToList();

convert web.config to appsettings.json in asp.net core

$
0
0

Hi Team,

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

how to convert web.config to appsettings.json in asp.net core 

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

How can I enable/disable a button based on input text Blazor Server app.

$
0
0

I have a simple Blazor Server app and would like to enable a button when there is text in an input, and disable the button if there is no text in the input. I have looked at and tried numerous examples, and have not come up with a working solution yet. This is for a page with a search button, which requires valid text before the search button becomes enabled.

So, when as a user enters a character in the text input, button is enable. If the user deletes all the text in the input, button is disabled.

If JavaScript is needed to solve this issue, I can deal with that, but please provide all required steps.

The code below does not work because the value of myInputText.Length is always zero. 

Note: if you run the code below in the debugger, the value of myInputText.Length is not always zero, but the the value is always one number behind, ex, first time EnableButton() is executed the value is zero, then one.  

Any help is greatly appreciated. 

Here is the simplified code:

@page "/InputExample"<h3>Input Example</h3><input type="text" @onkeyup="@(e => EnableButton(e))" @bind="myInputText" />

@if (disableState == true)
{
    <input type="button" value="I'm disabled" disabled="@buttonState">
}
else
{<input type="button" value="I'm not disabled">
}

@code 
{
    private string buttonState = "disabled";
    private string myInputText = "";
    bool disableState = true;

    public void EnableButton(EventArgs args)
    {
        if (myInputText.Length == 0)
        {
            disableState = true;
        }
        else
        {
            disableState = false;
        }
    }

}

The property 'JobTitle' is not a navigation property of entity type 'Job'. The 'Include(string)' method can only be used with a '.' separated list of navigation property names.

$
0
0

I am attempting to read related data across three tables in ASP.NET CORE MVC 2.2 with Entity Framework Core.

To be more specific I am using this tutorial to build my project https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/read-related-data?view=aspnetcore-2.2. I am using Eager Loading to read Job.JobTitle all the way from the Problem Index method. Reading this I realize I want to find where Problem navigation property that contains the Job entity of the JobTitle that the Problem is assigned to. But That would be a many to many relationship so I have thrown in a Result composite table to stop that.

From my research, adding the foreign key attributes can help. Which hasn’t. So how can I Render the JobTitle that the problem belongs too in the job index?

Job class:

public class Job
    {  

        public int ID { get; set; }
        public string JobTitle { get; set; }
        public string JobDescription { get; set; }
        public DateTime JobStartDate {get;set;}
        public DateTime JobDeadline {get;set;}
        public bool JobIsComplete{get;set;}
        
        public ICollection<Result> Results {get;set;}
    }

Result class:

    public class Result
    {        
        public int JobID {get;set;}
        public int ProblemID {get;set;}
        [ForeignKey("Job")]
public Job Job {get;set;} [ForeignKey("Problem")] public Problem Problem {get;set;} }

Problem class:

public class Problem
    {
        public int ID {get;set;}       
        public string ProblemTitle {get;set;}
        public string ProblemDescription {get;set;}
        public DateTime ProblemStartDate {get;set;}
        public string ProblemFileAttachments {get;set;}
        public int ProblemSeverity {get;set;}
        public bool ProblemComplete {get;set;}
public ICollection<Result> Result {get;set;} }

Index method of ProblemController (please see comment to find bug):

public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["ProblemIDSortParm"] = String.IsNullOrEmpty(sortOrder) ? "ProblemID_desc" : "";
            ViewData["ProblemTitleSortParm"] = String.IsNullOrEmpty(sortOrder) ? "ProblemTitle_desc" : "";
            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.JobTitle)                    
                            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 "ProblemStartDate":
                    problems = problems.OrderBy(p => p.ProblemStartDate);                    
                    break;
                case "ProblemStartDate_desc":
                    problems = problems.OrderBy(p => p.ProblemStartDate);                    
                    break;
                case "ProblemSeverity":
                    problems = problems.OrderBy(p => p.ProblemSeverity);
                    break;
                case "ProblemSeverity_desc":
                    problems = problems.OrderByDescending(p => p.ProblemSeverity);
                    break;   
                case "ProblemCompleteSortParm":
                    problems = problems.OrderBy(p => p.ProblemComplete);
                    break;
                case "ProblemCompleteSortParm_desc":
                    problems = problems.OrderByDescending(p => p.ProblemComplete);
                    break; 
                default:
                    problems = problems.OrderBy(p => p.ProblemTitle);
                    break;                 
            }

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

ProblemIndex view, (please see comment to find where I am having problem):

@model PaginatedList<Pitcher.Models.Problem>

@{
    ViewData["Title"] = "Problems";
}<h1>Index</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><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>
            @* RENDER Job Title here *@
                @Html.DisplayFor(modelItem => item.Result)
            @* END render Job Title here *@<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>






How to use redirect to open link in new tab in asp.net core 2.0.

$
0
0

Hi, I have a form on which submit I want to redirect to another page but I want to open the redirected page in a new tab.

if (requestedDownloadLink != null) 

      return Redirect(requestedDownloadLink);

c# data annotations validade Model, out of context of form binding (upload file)

$
0
0

I’m using asp.net core 3.1 razor pages and wanna validade a model on a upload process using data annotation.

My model is:

public class UserUpload
{
[Key]
public string UserId { get; set; }

[Required(ErrorMessage = "email must be informed"), DataType(DataType.EmailAddress)]
public string Email { get; set; }

[Required, MaxLength(100, ErrorMessage = "Maximum for name is 100 chars")]
public string Name { get; set; }

[Required]
public string Status { get; set; }
}

Processing each line of the file uploaded how can I use data annotations to validade records and get all errors?

I have a crud for the same model and validations are processed by the framework resulting ModelState identifying all errors but I don´t know how to use the same mechanism in the mass upload data.

Tks

How to work with selected items in a Dropdown or Select List

$
0
0

I have a Razor View in an Asp.Net Core Mvc project that takes a SelectList object as the model but I do not know how to then process the user selected items. Here is where I've got to so far:

The View Model I use to retrieve data to populate the dropdown list

public class PlayersListViewModel
{
public int id { get; set; }
public string name { get; set; }
public int gender { get; set; }
public DateTime dob { get; set; }
public string skill { get; set; }
public double rating { get; set; }
}

My Controller method that gets the data and then builds a SelectList as a model for the View

public ViewResult SelectEntrants()
{
IEnumerable<PlayersListViewModel> playersList = new List<PlayersListViewModel>().ToList();
playersList = _employeeRepository.PlayersList().ToList();
return View(new SelectList(playersList, "id", "name")); 
}

The View

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model SelectList
@{
ViewBag.Title = "Select Entrants";
}
<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Functions" asp-action="SelectEntrants">
<select id="id" multiple name="name" asp-items="Model" style="height:500px">
<option value="0">Please select</option>
</select>
<a asp-controller="functions" asp-action="showentrants"
class="btn btn-primary m-1">Show entrants count</a>
</form>
</body>
</html>

Using the above I get a multi-select dropdown in the View containing a list of names - great. But I have no idea how to get a list of selected items once the page is posted back to the server - I just can't find an example of a controller method that shows how to do that. Can anyone help?

Problem to use AsNoTracking query in master-detail entities.

$
0
0

Hi

I have 2  tables in master-details scenario as follow :

DefaultVisitProductHeaders -> Master table
DefaultVisitProductDetails -> Detail table

My problem is that when i load details data with AsNoTracking as follow :

List<DefaultVisitProductDetails> packageDetails = _dbContext.DefaultVisitProductDetails.AsNoTracking().Where(d => d.DefaultVisitProductHeaderRowID == gidPackageHeaderRowID).OrderBy(d => d.ProductID).ToList();
this.SetPackageDetailsList(packageDetails);

i'm facing error in SetPackageDetailsList method as follow :

InvalidOperationException: Error generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning': 
An attempt was made to lazy-load navigation property 'DefaultVisitProductHeaderRow' on detached entity of type 'DefaultVisitProductDetailsProxy'. Lazy-loading is not supported for detached entities or entities that are loaded with 'AsNoTracking()'. This exception can be suppressed or logged by passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.

Here is SetPackageDetailsList's body :

private void SetPackageDetailsList(List<DefaultVisitProductDetails> lstPackageDetails)
        {
            TempData["_lstPackageDetails"] = JsonConvert.SerializeObject(lstPackageDetails, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }); // Cause error!
        }

Where is the problem & how to solve it?

Thanks in advance

How to connect a script?

$
0
0

How to connect a script?
Have I connected the script correctly?

Used by:
ASP.NET Core

I want to implement an example - https://jsfiddle.net/
I start debugging without a server.

Model1.cs

namespace WebApplCore.Models
{
    public class Model1 
    {
        public int ID { get; set; }
        public string Title { get; set; }        

    }
}

HomeController.cs

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using WebApplCore.Models;


namespace WebApplCore.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            List<Model1> Items = new List<Model1>();
            Items.Add(new Model1() { ID = 1, Title = "Title 1"});
            Items.Add(new Model1(){ ID = 2, Title = "Title 2"});
            Items.Add(new Model1(){ ID = 3, Title = "Title 3"});

            return View(Items);

        }
    }
}


Index.cshtml

@using WebApplCore.Models;

@model IEnumerable<Model1>;<script src="https://code.jquery.com/jquery-3.5.1.min.js" type="text/javascript"></script><!-- CSS Includes --><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"><style type="text/css">
    .table {
        margin: 0 auto;
        width: 80%;
    }</style><body><div class="container"><table class="table table-sm table-hover table-striped"><thead class="thead-dark"><tr><th>
                        @Html.DisplayNameFor(model => model.ID)</th><th>
                        @Html.DisplayNameFor(model => model.Title)                        </th>                    ></tr></thead>
            @foreach (Model1 sVM in Model)
            {<tr><td>@sVM.ID</td><td><span class="item-display">@Html.DisplayNameFor(model => model.Title)</span><span class="item-field"><input type="text" value="@Html.DisplayNameFor(model => model.Title)" /></span></td>                    </tr>
            }</table></div><script>$(document.documentElement)
            .on("click", "span.item-display", function (event) {$(event.currentTarget)
                    .hide()
                    .next("span.item-field")
                    .show()
                    .find(":input:first")
                    .focus()
                    .select();
            })
            .on("keypress", "span.item-field", function (event) {
                if (event.keyCode != 13)
                    return;

                event.preventDefault();

                var $field = $(event.currentTarget),$display = $field.prev("span.item-display");$display.html($field.find(":input:first").val());$display.show();$field.hide();
            });</script></body>





Viewing all 9386 articles
Browse latest View live


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