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

Create Custome class of AuthorizeAttribute implementation issue in mvc core

$
0
0

Hi,
I create a class which implement AuthorizeAttribute Interface with override method HandleUnauthorizedRequest in mvc core.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using IdentityTest.DBModel;

namespace IdentityTest.CustomFolder
{
public class CustomErrorTexelMobile: AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
using (MobileEntities db = new MobileEntities())
{
var res = db.SelfServeAdmins.FirstOrDefault(sid => sid.MobileSignOnEnabled == true);
if (res == null)
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new {controller = "PermissionError", action = "AccessDenied"}));
}
}
}
}
}

Compile Time error: Error CS7069 Reference to type 'RouteValueDictionary' claims it is defined in 'System.Web', but it could not be found

How can to slove this issue. Which namespace necessary for MVC Core against This issue.


Select 2 dropdown storing flag name and id how

$
0
0
<div class="votecell post-layout--left"> <div class="js-voting-container grid fd-column ai-stretch gs4 fc-black-200" data-post-id="63604290"> <div class="js-vote-count grid--cell fc-black-500 fs-title grid fd-column ai-center c-pointer" itemprop="upvoteCount" data-value="1" role="button" data-s-tooltip-placement="right" data-controller="null s-tooltip" aria-describedby="--stacks-s-tooltip-7n5oxt3q" tabindex="0">I am using select 2 to give myself a country list found in another so post but I need some way of being able to select the flag that i am using in edit mode. The dropdown is built up as such , the country is shorted for completeness of this question. I am using asp.net core 3.1.7 and ef core 3.1.</div> </div> </div> <div class="postcell post-layout--right"> <div class="post-text" itemprop="text">

Then in my edit page I have the following.

<div class="form-group">
    @Html.LabelFor(m => m.CountryOfBirth)<span asp-validation-for="CountryOfBirth" class="text-danger"></span><select asp-for="CountryOfBirth" class="form-control select2" style="height:35px" name="Flag"><option>Please select Country Of Birth</option></select><span asp-validation-for="CountryOfBirth" class="text-danger"></span></div>

As you can see right away the issue is that I am storing a Country string rather than an id in the iso countries Variable however that doesnt work as I would need a id to be able to bind to the Select above.

But i need the country string to be able to pic up the flag in the flags.css file that i am using from here https://github.com/lipis/flag-icon-css

In My Javascript

<script>$(function () {
    //Initialize Select2 Elements$('.select2').select2()
    var isoCountries = [
        { id: 'Uk', text: 'United Kingdom' },
        { id: 'US', text: 'United States' }
 ];

function formatCountry(country) {
        if (!country.id) { return country.text; }
        var $country = $(
            '<span class="flag-icon flag-icon-' + country.id.toLowerCase() + ' flag-icon-squared"></span>' +
            '<span class="flag-text">' + country.text + "</span>"
        );
        return $country;
    };

    //Assuming you have a select element with name country
    // e.g. <select name="name"></select>$("[name='Flag']").select2({
        placeholder: "Please Select a country",
        templateResult: formatCountry,
        data: isoCountries
    });
});</script>

</div> </div>

integrate a cms into existing .net core mvc application

$
0
0

Say I have a .net core mvc application with controller configuration like this:

can I do like that?
I want the cms & my web app run separately with might share the same database.

which cms engine is recommended for me? orchard or dotnetnuke or anything else?

How to generate url to friendly route with asp-page

$
0
0

I have friendly route configured in startup configureservices

services.AddRazorPages()
.AddRazorPagesOptions(options =>
 {
options.Conventions.AddPageRoute("/Admin/PagesWithTables/ShowLicencjeTable", "ShowLicencjeTable");
});

I want to generate url with asp-page 

<li class="nav-item">
    class="nav-link text-dark" asp-area="" asp-page="/ShowLicencjeTable">moje licencje</a>
</li>

but I get empty url: href="". How can I configure my url with tag helper?

Please I need help with filtering my logs

$
0
0

I am using the defualt .net logging. I have done alot but when I put my app in production it loggs a lot of db queries. I passed my log into my repository classes with the intension of logging exception any time there is a failure in production.

how can I Filter my logs. my app is hosted in docker container. Please I would share some codes kindly help me out. been on this for weeks yet not working.

public void Configure(IApplicationBuilder app, DatabaseContext databaseContext, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            app.UseCors("AllowAll");    

            //This code is going to facilitate the logging of errors
            loggerFactory.AddFile("Logs/mylog-{Date}.txt");

            ILogger logger = loggerFactory.CreateLogger<Startup>();
Program.cs
 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
             WebHost.CreateDefaultBuilder(args)
               .ConfigureLogging((context, logging) => {
               var env = context.HostingEnvironment;
               var config = context.Configuration.GetSection("Logging");
              // ...
              logging.AddConfiguration(config);
               logging.AddConsole();
              //logging.SetMinimumLevel(LogLevel.Debug);
              // ...
               logging.AddFilter("Default", LogLevel.Information);
               logging.AddFilter("Microsoft", LogLevel.Warning);
               logging.AddFilter("System", LogLevel.Warning);
                   logging.AddFilter("System", LogLevel.Debug); 
                  logging.AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information);
               logging.AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace);
                 //  logging.AddFilter("");
              })
                .UseStartup<Startup>();

The a sample repo that calls it.

 public class SettingRepository : ISettingRepository, IDisposable
    {

        //Declaring the variables of the repository
        private DatabaseContext context = null;
        private bool disposed = false;

        private ILogger logger { get; set; }

        public SettingRepository(DatabaseContext context, ILogger<SettingRepository> logger)
        {
            this.context = context;
            this.logger = logger;
        }

Logs has alot of junks in it. Please what can I do to simplify from my codes.

Thanks alot.

Js ComboTree Pluggin : to change the combotree background color into white

$
0
0

Hi 

I am using Javascript Combotree pluggin. At the moment combo tree  is transparent to the the screen color . So  the users cannot see the  the its content. Screen background color is blue  and the combo tree is transparent to the screen.  So I am trying to change its transparent into white.

I wonder it is working in chrome browser perfect, but not working IE. So please can you help how to change its background color into white. Any help with code would be very appreciated. My code given below

<div class="form-group"><label class="control-label control-label-left col-sm-3" for="field2">User Depots & Departments</label><div class="controls col-sm-9"><input type="text" id="ddlDepotMapping" placeholder="Select" /><input type="hidden" id="hfDepotMapping" asp-for="SelectedDepotMapping" /></div></div>

I am calling the function in script

<script>
FillDepartmentsMappings(@ViewBag.DepotDepartmentMapping);</script>
function FillDepartmentsMappings(defaultSelected) {$.ajax({
        type: "GET",
        url: "/User/GetDepotDepartemntsForMap",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {$('#ddlDepotMapping').comboTree({
                source: data,
                isMultiple: true,
                cascadeSelect: true,
                collapse: true,
                selected: defaultSelected
            });
        },
        failure: function (response) {
            console.log(response.responseText);
        },
        error: function (response) {
            console.log(response.responseText);
        }
    });



Select Asp-items not adding data to database.

$
0
0

Hello, I have been having really strange issue with asp-items, I am using ViewBag to pass a List<SelectListItem> object to asp-items but in return, it's not adding anything to my database, even though when I see the source through browser it shows every value and text of Select option fine. The select asp-items is as follows and "Manufacturers" is actually a foreign key in "Dinghies" Table.

div class="form-group"><label asp-for="Manufacturers" class="control-label"></label><select class="form-control" asp-for="Manufacturers" asp-items="ViewBag.Manufacturers"></select><span asp-validation-for="Manufacturers"></span></div>

Let me explain more, Here are some of the controller methods against the form mentioned above

public IActionResult AddDinghies() {
            List<SelectListItem> List1 = new List<SelectListItem>();
            List1 = SelectListConverter(_context3.Manufacturers); //.ToList()
            ViewBag.Manufacturers = List1;
            return View();
        }
//Method to Convert IEnumerable to SelectListItem
private List<SelectListItem> SelectListConverter(IEnumerable<Manufacturers> Manufacturers)
        {
            List<SelectListItem> ListOfMan = new List<SelectListItem>();
            foreach (var manufacturer in Manufacturers)
            {
                ListOfMan.Add(new SelectListItem
                {
                    Value = manufacturer.id.ToString(),
                    Text = manufacturer.Manufacturer //Name of manufacturer
                });
            }
            return ListOfMan;
     }

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddDinghies([Bind("id,Name,OlympicBoat,Type,TypeCrew,TypePurpose,Length,Beam,Draft,SailAreaUpwind,GennakerSailArea,SpinnakerSailArea,SAOptional,SAOptional2,Weight,PYS,ImagePath,CrewPersons,CrewWeight,Description,DesignBy,DesignYear,OlympicSectionViewSwitch,Manufacturersid")] Dinghies dg)
        {
            if (ModelState.IsValid)
            {
                _context2.Add(dg);
                await _context2.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(dg);
        }

Actually whats wrong is happening within this code is that every entity from the View form is being passed to the "Dinghy" table but the Manufacturersid which is the foreign key and is being passed from asp-items always remains empty/null. 

Any help or hint will be highly appreciated, I can provide more explanation/code if anybody wants. I know its tough to read this much code but I really need help in this. Thanks a lot! 

Startup.cs KeyVault - Production & Development

$
0
0

Hi,

Basically I got a slot for development url. I want different url use different key vault.

I have 2 set of key vault to store database connection, 1 for Production & another 1 for development.

How can I check the hostname in web.config to decide which keyvault to use?

--Production

KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));
            var secret = keyVaultClient.GetSecretAsync(vaultAddress, "DatabaseConnStr", "xxxxxxxxxxxxx").GetAwaiter().GetResult();
            var storagePrimaryAccessKey = secret.Value;
            connectionString = storagePrimaryAccessKey;

if(host=="https://dev.azurewebsites.com)   //I got problem at the host

{

secret = keyVaultClient.GetSecretAsync(vaultAddress, "DatabaseConnStrDev", "xxxxxxxxxxxxx").GetAwaiter().GetResult();
            var storagePrimaryAccessKey = secret.Value;
            connectionString = storagePrimaryAccessKey;
}

Pease advise.

Thanks.

Regards,

MIcheale


web config file is inaccessible error

$
0
0

Hi all,

This morning something strange happened.

I got "web config file is inaccessible error" and now my published net core 2 project does not work in the server.

Do you have any idea what can cause this?

using Microsoft.AspNetCore.Identity.UI.Services

$
0
0

There is a problem on Asp.net Core 5.0 Preview

Microsoft.AspNetCore.Identity.UI.Services is not available for ASP.NET Core 5.0 Preview. You have been redirected to the newest product version this page is available for.

It is working on Asp.Net Core 3.0

How to sent email for this example :)

https://docs.microsoft.com/en-US/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs=visual-studio

And this example: 

https://docs.microsoft.com/en-US/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-5.0&tabs=visual-studio#create-full-identity-ui-source

will you remove these example about emailsender? and why ?

Fetching Sub Records 2 levels deep when using Stored Procedure

$
0
0

I have a hierarchical design as follows : 

Request > Fields (multiple) > FieldChoices (multiple)

So each request can have multiple fields, and each field in turn multiple field choices. I then need to render these on my view as form controls (select lists) with the choices displayed against each field.

So my Fields object has FieldChoices as a property :

        public IEnumerable<FieldChoice> Choices { get; set;}

When fetching records at the Fields level I am using a stored procedure as the values can come from multiple tables, and the selection is subject to some convoluted logic (user levels etc). This all works fine and I can render the controls out, the issue I am having is when I want to then fetch the list of choices against each field.

I did try using the .Include option in my code  :

        public IEnumerable<Field> GetRequestFields(string gar, int selection, int wholesale, int level)
        {
            // setup params
            var pGAR = new SqlParameter { ParameterName = "GAR", Value = gar };
            var pSel = new SqlParameter { ParameterName = "SelectionId", Value = selection };
            var pWholesaler = new SqlParameter { ParameterName = "WholesalerID", Value = wholesale };
            var pLevel = new SqlParameter { ParameterName = "UserLevel", Value = level };
            // setup stored procedure
            string query = "EXEC sp_Get_APICallFields @GAR, @SelectionId, @WholesalerID, @UserLevel";
            // perform query
            var flds = context.Fields.FromSqlRaw(query, pGAR, pSel, pWholesaler, pLevel)
                .Include(e => e.Choices)
                .ToList();
            return flds;
        }

But as I am using a Stored Procedure for the initial fetch I get the usual error which I do understand :

InvalidOperationException: FromSqlRaw or FromSqlInterpolated was called with non-composable SQL and with a query composing over it. Consider calling `AsEnumerable` after the FromSqlRaw or FromSqlInterpolated method to perform the composition on the client side.

What is the best way to effect this arrangement? I can't query the db directly using Linq / EF as I really need to use the Stored Procedure to keep things tidy - how can I go about getting the sub records for the Field Choices and attribute them to each field?

Many Thanks

Prevent default submit action does not work in partial view to call method by Ajax

$
0
0

Hi

I'm returning a list for child class ArticleImages to call it as a partial view in Articles class like this:

public IList<ArticleImages> ArticleImages { get; set; } = new List<ArticleImages>();

Then Include it in Articles get edit method like this:

    public class ArticlesController : Controller
    {
        private readonly ApplicationDbContext _context;

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

        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var articles = await _context.Articles
                .Include(n => n.ArticleImages)
                .FirstOrDefaultAsync(n => n.Id == id.Value);
            if (articles == null)
            {
                return NotFound();
            }
            return View(articles);
        }

Then calling the list as a partial view in Articles/Edit like this:

 @{ await Html.RenderPartialAsync("~/Views/ArticleImages/ParArticleImages.cshtml", Model); }

Then Trying to call this method in ArticleImagesTrController to add a new record (after call of get method by ajax successfully) in the previous Edit view:

        [HttpPost]
        public IActionResult Add([FromBody]ArticleImagesTr obj)
        {
            _context.Add(obj);
            _context.SaveChanges();
            return new JsonResult(obj);
        }

Now when I try to call the previous method by Ajax in ParArticleImages partial view like this:

@model Articles

@*Some code*@

    <div class="modal fade" id="AjaxMod" tabindex="-1" role="dialog" aria-labelledby="addContactLabel" aria-hidden="true"><div class="modal-dialog modal-lg" role="document"><div class="modal-content mod"><div class="modal-header"><h5 class="modal-title" id="addContactLabel">Translation</h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button></div><div class="modal-body"><form id="save" name="form"><div class="row"><div class="col-md-3"><div class="form-group"><div><label>Language</label><select class="form-control" id="la"><option value="0"> Arabic</option><option value="1" selected> English</option></select></div><input type="text" class="form-control" id="masid" name="mas-id" /></div></div></div><div class="row"><div class="col-md-12"><div class="form-group" dir="ltr"><label>Title</label><input type="text" id="ti" class="form-control" /><label>Details</label><textarea rows="9" class="form-control" id="de"></textarea></div></div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal" name="cl">Close</button><button type="submit" class="btn btn-primary">Save</button></div></form></div></div></div></div><script>$(function () {$("#save").submit(function (e) {
            e.preventDefault();
            var options = {};

            options.url = "/ArticleImagesTr/Add";
            options.type = "POST";

            var obj = {};
            obj.langId = select;

            obj.articleImageId = $('#masid').val(); // I have it by Ajax get method successfully
            obj.imageTitle = $("#ti").val();
            obj.details = $("#de").val();

            options.data = JSON.stringify(obj);
            options.contentType = "application/json";
            options.dataType = "json";
            if (!obj.imageTitle || !obj.details) {
                toastr.error('All fields required!', { timeOut: 5000 });
            }
            else {
                options.success = function (msg) {
                    toastr.success('Saved!', { timeOut: 5000 });
                };$.ajax(options);$('#AjaxMod').modal('hide');
            }

            options.error = function () {
                toastr.error('Not done!', { timeOut: 5000 });
            };

        });
     });
</script>

Now when I press submit button it returned blank page as the submit of Edit view it self not calling the previous method by Ajax.

Why? and how to solve please?

Visual Studio Code for MacOS v1.48: scaffolding via Explorer right-click/context menu for Razor Pages

$
0
0

In Visual Studio Code for Mac v1.48, working thru the Razor Pages tutorial at https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages ... there are 'Visual Studio For Mac'-specific instructions that I cannot replicate: in the File Explorer, right-clicking folder I do not see, 'Add >', nor any Razor Pages scaffolding-related items (e.g., 'New File ... 'with options for 'General', 'Empty Class', etc.)

Can someone please tell me which specific extensions I might be missing that would account for this, or what I might have misconfigured in my existing setup (mostly defaults, with C# of course, also ASP.NET Core Snippets, ASP.NET Helpers, etc. installed)

Thank you,

Whiskey T.

Problem with writing LINQ for component view (Dropdown menu)

$
0
0

Hi guys,

My website will have 3 levels of dropdown menu on navbar. Categories -> Subcategories -> NestedCategories

All these data must be fetched from database using good LINQ on InvokeAsync() action. In default view I use view model named MenusModel.

@model IEnumerable<Samirad.Models.ViewModels.MenusModel>
@using Samirad.Models.ViewModels
@using Samirad<ul class="dropdown-menu" id="catmenu">
    @foreach (MenusModel item in Model)
    {<li><div class="dropdown-item family"><a href="">@item.Category.Name</a><ul class="submenu">
                    @if (item.Subcategories != null && item.Subcategories.Count() > 0)
                    {
                        foreach (Subcategory component in item.Category.Subcategories)
                        {<li><a class="dropdown-item">@component.Name</a><ul class="secondsub">
                                    @if (item.NestedCategories != null && item.NestedCategories.Count() > 0)
                                    {
                                        foreach (NestedCategory element in component.NestedCategories)
                                        {<li><a class="dropdown-item">@element.Name</a></li>
                                        }
                                    }</ul></li>
                        }

                    }
                </ul></div></li>
    }</ul>

And this is my InvokeAsync() action where I cannot define NestedCategories  in the right way.

namespace Samirad.ViewComponents
{
    public class MenuViewComponent: ViewComponent
    {
        private readonly SamirDbContext _samirDbContext;

        public MenuViewComponent(SamirDbContext samirDbContext)
        {
            _samirDbContext = samirDbContext;
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            var menu = await _samirDbContext.Categories.Include(x => x.Subcategories).ThenInclude(y => y.NestedCategories).
                                                      Select(x => new MenusModel()
                                                      {
                                                          Category = x,
                                                          Id = x.Id,
                                                          Subcategories = x.Subcategories.Select(y => new Subcategory()
                                                          {
                                                              Id = y.Id,
                                                              Name = y.Name
                                                          }),  NestedCategories = ......
                                                      }).ToListAsync();
return View(menu); } } }

I cannot reach subcategories in order to get nestedcategories from there to define them to Nestedcategories of the viemodel (MenusModel).

Please, help me with this. 

Thanks in advance

May I ask for help with Navigation Properties?

$
0
0

In the course of my studies, I went through a tutorial on the Unit of Work pattern at this link:

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

The tutorial is 7 years old, so I was trying to refit it for Core 3.1.

Here's the student model:

    public class Student
    {
        public int StudentID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }

Next is the Enrollment model:

    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public Grade? Grade { get; set; }
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }

And finally, the Course model:

    public class Course
    {
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }

In the tutorial, it shows how you fetch detail information via the controller:

Student student = db.Students.Find(id);

In my test, I found that the navigation properties for Enrollment, and the Course title were null. So I attempted to modify the select to this:

Student student = await mydb.Students.Include(e => e.Enrollments).Where(e => e.StudentID == id).FirstOrDefaultAsync(s => s.StudentID == id);

My modification fetched all the Enrollment data, but I still can't figure out how to get a Course Title for each enrollment record.
I apologize if this is a convoluted way to ask my question - I'm just puzzled how to get course data.

The output should show the one student's name, then all his enrollments. Those enrollments should include a course title as well.

In T-SQL, it might look like this:

SELECT a.Lastname, a.FirstMidName, a.EnrollmentDate, b.Grade, c.Title FROM Students a
INNER JOIN Enrollments b ON b.StudentID = a.StudentId
INNER JOIN Courses c ON c.CourseID = b.CourseID
WHERE a.StudentID = 1

Any advice on how I can select all that data so I can get it into a View?


I have a problem with Docker

$
0
0

My project is working on IIS Express. When I use Docker, I have a problem that is about sql server connection. 

Microsoft.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'

But I said that my project is working on IIS Express... ? 

Read public key in .net core 2.2

$
0
0

How can i read  third party public key in .net core 2.2 rest api .The public key extension is .cer

Why Does MSFT use Bind and not the object itself when scafolding

$
0
0

Why does the code in the scaffolder use the bind object and what is the difference in it to using just the object.

public async Task<IActionResult> Edit(int id, [Bind("Id,FirstName,Address1,Address2,City,County,PostCode,MiddleName,Role,PoiReason,LastName,Nationallity,DOB,Age,Alias,PlaceOfBirth,CountryOfBirth,Deceased,DeceasedDate,AddressId,EmailAddress,FacebookUrl,TwitterUrl,LinkedInUrl,CopmanyName,CompanyAddress,StartDate,EndDate,isDeleted,isActive,CreatedDate,CreatedBy,Tattoos")] POI pOI) {
            if (id != pOI.Id) {
                return NotFound();
            }
}
public async Task<IActionResult> Edit(int id, POI pOI) {
            if (id != pOI.Id) {
                return NotFound();
            }
}

I was just curious as to why the scaffolding used the other approach would a form not automatically bind to the object it is attached to ?. I am using asp.net core 3.1.7 in case that changes the answer was just always curious

Is their any extra steps if was to use the other method in the pages that the scaffolding did for me would I have to do any other steps to have the form values be in my object?

variable 'ct' of type 'System.Threading.CancellationToken' referenced from scope '', but it is not defined

$
0
0

Hi,

I have used the following LINQ code for my viewcomponent menu, and faced exception written in Title which I could'n understand why. I even didn't declare variable 'ct' anytwhere. Did someone face such issue? 

public async Task<IViewComponentResult> InvokeAsync()
        {
                var menu = await _samirDbContext.Categories.Include(x => x.Subcategories).ThenInclude(y => y.NestedCategories).
                                                          Select(x => new MenusModel()
                                                          {
                                                              Category = x,
                                                              Id = x.Id,
                                                              Subcategories = x.Subcategories,
                                                              Subcategory = x.Subcategories.FirstOrDefault(),
                                                              NestedCategories = x.Subcategories.FirstOrDefault().NestedCategories.Select(z => new NestedCategory()
                                                              {
                                                                  Id = z.Id,
                                                                  Name = z.Name
                                                              })

                                                          }).ToListAsync();
                
                return View(menu);
                                                                                       
        }

Thanks in advance

Foreign Key properly set but can't access the data through foreign key.

$
0
0

Hello Guys, Hope everyone is doing well. First, I would like to thank everyone for contributing to this forum, I am new to ASP.NET Core and here people helped me a lot to solve my problems, I was having a problem to set foreign key in my database and I posted the issue here which got solved but it lead me to a new problem so I decided to make a separate thread for it in a relevant category.

Okay so, I have three classes, Dinghy, Manufacturer and ClassAssociation, each Dinghy have 1 manufacturer and 1 class association and so each table of Dinghy includes its respective foreign keys for manufacturer and class association. The problem is that, when I add Dingies to database through a form, everything works well and table of Dinghies receives the IDs of Manufacturer and Class Association, but when I proceed to display the name of Manufacturer and Class Association using the foreign keys, it shows null. Debugging has shown me that the object of Manufacturer and Class Association is storing null. Why is it so when I have properly configured the foreign keys?

I am attaching the relevant code for you guys to dig out the issue.

.CSHTML File (I am using this syntax to display the data) 

<td>
                @Html.DisplayFor(modelItem => item.Manufacturers.Manufacturer)</td><td>
                @Html.DisplayFor(modelItem => item.CA.CAName)</td>

ListDinghies Action in Controller

public async Task<IActionResult>ListDinghies(){returnView(await _context2.Dinghies.ToListAsync());}

AddDinghies Post Action in Controller

public async Task<IActionResult>AddDinghies([Bind("id,Name,OlympicBoat,Type,TypeCrew,TypePurpose,Length,Beam,Draft,SailAreaUpwind,GennakerSailArea,SpinnakerSailArea,SAOptional,SAOptional2,Weight,PYS,ImagePath,CrewPersons,CrewWeight,Description,DesignBy,DesignYear,OlympicSectionViewSwitch,ManufacturerID,ClassAssociationID")]Dinghies dg){if(ModelState.IsValid){//_context2.Manufacturers.Include(e => e.Manufacturer).FirstOrDefault(m => m.id == );
                _context2.Add(dg);
                await _context2.SaveChangesAsync();returnRedirectToAction(nameof(Index));}returnView(dg);}

Dinghies.cs (Only showing section where foreign keys and navigation properties are added)

[ForeignKey("Manufacturers")]publicintManufacturerID{get;set;}publicManufacturersManufacturers{get;set;}[ForeignKey("CA")]publicintClassAssociationID{get;set;}public CA CA {get;set;}

I have searched a lot on internet but couldn't find the solution, I believe only an expert can figure out the problem. Thanks

Viewing all 9386 articles
Browse latest View live


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