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

How to refill previously selected values on the criteria dropdown when it returns from Report view to Report criteria

$
0
0

After viewing the report , there is a back button in report view to go back to report criteria. But when I  going back to criteria ,   how can refill all the criteria value same as before when I had selected to generate the report. At the moment  when I coming back to criteria, all value would be initialized. Please can I ask you to help me with suggested code to bring the previously selected value in criteria view

Controller code

[HttpPost]
        public IActionResult AttendanceReportCriteria(ReportViewModel report)
        {
            List<SelectListItem> depo = new List<SelectListItem>();
            List<SelectListItem> dept = new List<SelectListItem>();
            dept = EmployeeService.GetUserDepartments(HttpContext.Session.GetInt32("UserID") ?? 0, connectionSettings);
            depo = EmployeeService.GetUserDepots(HttpContext.Session.GetInt32("UserID") ?? 0, connectionSettings);
            depo.RemoveAt(0);
            dept.RemoveAt(0);
            ViewBag.UserDepartments = dept;
            ViewBag.UserDepots = depo;
            List<SelectListItem> employees = new List<SelectListItem>();
            for (int k = 0; k < report.Depot.Count; k++)
            {
                for (int l = 0; l < report.Department.Count; l++)
                {
                    List<SelectListItem> emp = new List<SelectListItem>();
                    emp = EmployeeService.GetEmployeesForDepot(Convert.ToInt32(report.Depot[k]), Convert.ToInt32(report.Department[l]), connectionSettings);
                    emp.RemoveAt(0);
                    employees.AddRange(emp);
                }
            }
            ViewBag.Employees = employees;
            DateTime fromDate = new DateTime();
            DateTime toDate = new DateTime();
            if (report.FromDate != "" && report.ToDate != "" && report.FromDate != null && report.ToDate != null)
            {
                fromDate = DateTime.ParseExact(report.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                toDate = DateTime.ParseExact(report.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

            }
            else
            {
                fromDate = DateTime.ParseExact(DateTime.UtcNow.ToShortDateString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                toDate = DateTime.ParseExact(DateTime.UtcNow.ToShortDateString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);

            }
           
            List<DepotModel> depotList = new List<DepotModel>();
            List<EmployeeModel> employeeList = new List<EmployeeModel>();
            List<AttendanceLogModel> log = new List<AttendanceLogModel>();
            log = ReportService.GetEmployeeAttendanceReport(String.Join(",", report.Depot), String.Join(",", report.Department), String.Join(",", report.Employee), fromDate, toDate, connectionSettings);
            ViewBag.AttendanceLogs = log;
            return View("AttendanceReport", report);
        }

[HttpPost]
        public IActionResult AttendanceReport()
        {
            return View("AttendanceReportCriteria");
        }

Report criteria html

<div class="container-fluid shadow"><div class="row my-sticky-element" style="display: block;"><label class="control-label-left padding-left-twenty col-sm-6" for="field1">ATTENDANCE REPORT - Criteria </label></div><hr style="margin-top:unset" /><div class="row col-md-12 yellow_text @ViewBag.IsFilter" id="divFilters"><div class="row col-sm-12"><div class="row"><div class="col-sm-4"><div class="form-group"><label class="control-label control-label-left col-sm-4" for="field1">Date From</label><div class="controls col-sm-8"><div class='input-group date' id='FromDatePicker'><input type='text' asp-for="FromDate" class="form-control " /><span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div></div></div></div><div class="col-sm-4"><div class="form-group"><label class="control-label control-label-left col-sm-4" for="field2">Date To</label><div class="controls col-sm-8"><div class='input-group date' id='ToDatePicker'><input type='text' asp-for="ToDate" class="form-control" /><span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div></div></div></div></div></div><div class="row col-sm-12"><div class="row col-sm-8"><div class="form-group"><label class="control-label control-label-left col-sm-2" for="field2"> Depot</label><div class="controls col-sm-10" style="padding-right: 0px !important;"><select id="dropdownDepot" class="form-control" multiple asp-for="Depot" onchange="FillEmployeeDropdown()" asp-items="@ViewBag.UserDepots" data-role="select"></select></div></div></div><div class="col-sm-8 row"><div class="form-group"><label class="control-label control-label-left col-sm-2" for="field2"> Department</label><div class="controls col-sm-10" style="padding-right: 0px !important;"><select id="dropdownDepartment" multiple class="form-control" asp-for="Department" onchange="FillEmployeeDropdown()" asp-items="@ViewBag.UserDepartments" data-role="select"></select></div></div></div><div class="col-sm-8 row"><div class="form-group"><label class="control-label control-label-left col-sm-2"> Employee</label><div class="controls col-sm-10" style="padding-right: 0px !important;"><select id="dropdownEmployee" multiple class="form-control" asp-for="Employee" asp-items="@ViewBag.Employees" data-role="select"></select></div></div></div></div></div><div class="col-sm-3"><button type="submit" class="btn btn-primary form-control">Show</button></div>

report chtml file

<div class="container-fluid" id="AttendanceReport"><div class="row"><form asp-controller="Report"
              asp-action="AttendanceReport"
              data-ajax="true"
              data-ajax-method="POST"
              data-ajax-mode="replace"
              data-ajax-update="#content"
              class="form-horizontal"
              role="form"
              data-parsley-validate novalidate><div class="container-fluid shadow"><div class="row my-sticky-element" style="display: block;"><label class="control-label-left padding-left-twenty col-sm-6" for="field1">ATTENDANCE REPORT  </label></div><hr style="margin-top:unset" /><div class="row col-sm-8 padding-top-ten" id="divActions"><div class="form-group"><div class="center-block"><div class="col-sm-2"></div><div class="col-sm-3"><button type="submit" class="btn btn-primary form-control" id="btnShow">Back</button></div></div></div></div></div><div><hr style="margin-top:unset" /></div><!--Report Content--><div>
                @if (@ViewBag.AttendanceLogs == null)
                {<div class="row col-sm-8 text-center yellow_text"><span>No records found</span></div>
                }
                else
                {<div class="table-responsive"><div class="col-sm-12 portlet light @ViewBag.IsReport" id="divReport"><table id="example" class="display text-nowrap" c cellspacing="0" style="width:100%"><thead><tr><th>
                                            Depot Name</th><th>
                                            Employee Name</th><th>
                                            Date</th><th>
                                            Clocked In</th><th>
                                            Clocked Out</th><th>
                                            N.Attendance</th></tr></thead><tbody>
                                    @foreach (AttendanceLogModel log in ViewBag.AttendanceLogs as List<AttendanceLogModel>)
                {<tr><td> @log.DepotName</td><td> @log.EmployeeName</td><td> @log.FromDate</td><td> @log.ClockedIn</td><td> @log.ClockedOut</td><td> @Convert.ToInt32(@log.IsNormalAttendance)</td></tr>

}

                                </tbody></table></div></div>

                }
            </div></form></div></div>

Please help would be very appreciated

With Thanks

Pol


share link for telegram ,...

$
0
0

hi

I want to share a link via URL scheme lets say for Telegram, whatsup ,... in any browser .

Please help me

Dynamic breadcrumbs in mvc core

$
0
0

Hi 

I need some breadcrumb in one page.but I do not know how I can do it

for example :

Home/Cat1/product1
Home/Cat2/Product1
Home/Cat3/Product1

I see some packages for example SmartBreadCrumb,dntbreadcrumb ,.. but these packages work one breadcrumb every page not some breadcrumb in one page

Existing image file doesn't come in edit view

$
0
0

Hi guys,

As previously I discussed, I have a Post model for which I've written CRUD in my admin view. The post model has the following properties.

public class Post
{
public int Id { get; set; }
[Required]
[MaxLength(55)]
public string Title { get; set; }
[Required]
[MaxLength(145)]
public string Description { get; set; }
public string Image { get; set; }
[Required]
public DateTime CreatedDate { get; set; }
[Required]
public DateTime ExpirationDate { get; set; }
public string URL { get; set; }
public Company Company { get; set; }
public int CompanyId { get; set; }
public Subcategory Subcategory { get; set; }
public int SubcategoryId { get; set; }
public bool SpecDiscount { get; set; }
public bool Gifted { get; set; }
public Detailed Detailed { get; set; }
}

Both Create & Edit Post actions work, but when I click any created post to edit, after getting that post's Id, it shows all of the properties (title, desc, etc) in the relevant fields except image. Of course, if I want to change image, there is no need to see its file name and file there as I'll update it. But, if I want to change other property, say for ex. Title, everytime I have to reupload its image file which gives me inconvenience in edit process.

Here is Create Post [post] and Edit Post [get] actions:

PostController

public class PostController : Controller
{
private readonly IHostingEnvironment _env;
private readonly OfferDbContext _offerDbContext;

public PostController(IHostingEnvironment env, OfferDbContext offerDbContext)
{
_env = env;
_offerDbContext = offerDbContext;
}


[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Postadd(Post post, IFormFile file, DateTime startDate, DateTime endDate, bool gifted, bool specDiscount)
{
if (ModelState.IsValid)
{
if (file == null || file.Length == 0)
{
ModelState.AddModelError("", "No file selected");
return View();
}

string mypath = Path.Combine(_env.WebRootPath, "images", Path.GetFileName(file.FileName));

using (var stream = new FileStream(mypath, FileMode.Create))
{
await file.CopyToAsync(stream);
}

AdminPostModel postModel = new AdminPostModel();
postModel.Companies = await _offerDbContext.Companies.ToListAsync();
postModel.CompanyList = await _offerDbContext.Companies.Select(x => new SelectListItem()
{
Value = x.Id.ToString(),
Text = x.Name

}).ToListAsync();

if(gifted == true)
{
post.Gifted = true;
}

if(specDiscount == true)
{
post.SpecDiscount = true;
}
post.CreatedDate = startDate;
post.ExpirationDate = endDate;
post.Image = file.FileName;
_offerDbContext.Posts.Add(post);
await _offerDbContext.SaveChangesAsync();
return RedirectToAction("Admin", "Admin");
}
else
{
ModelState.AddModelError("", "Couldn't create");
return View();
}

}

[HttpGet]
public async Task<IActionResult> EditPost(int Id)
{
AdminPostModel postModel = new AdminPostModel();
postModel.Post = await _offerDbContext.Posts.SingleOrDefaultAsync(x=> x.Id == Id);
postModel.Companies = await _offerDbContext.Companies.ToListAsync();
postModel.CompanyList = await _offerDbContext.Companies.Select(x => new SelectListItem()
{
Value = x.Id.ToString(),
Text = x.Name

}).ToListAsync();

postModel.SubcategoryList = await _offerDbContext.Subcategories.Select(y => new SelectListItem()
{
Value = y.Id.ToString(),
Text = y.Name

}).ToListAsync();

return View(postModel);
}

EditPost View

@model Foroffer.Models.ViewModels.AdminPostModel

@{
Layout = "AdminLayout";
}

<section class="buttonpanel">
<h5 style="font-weight:bold">Edit Post</h5>
</section>
<section class="posts">
<div class="post-container">
<div class="row">
<div class="col-lg-3 col-md-4 col-sm-6 col-12">
<form method="post" asp-action="EditPost" asp-controller="Post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly"></div>
<input type="hidden" asp-for="Post.Id" />
<label asp-for="Post.Title" style="width: 45px">Title</label>
<input asp-for="Post.Title" class="postinput" type="text"><br>
<span asp-validation-for="Post.Title"></span>
<label asp-for="Post.Description" style="width: 45px">Description</label><br>
<textarea asp-for="Post.Description" class="texbox" type="text"></textarea><br>
<span asp-validation-for="Post.Description"></span>
<label asp-for="Post.Image">Upload Image</label>
<input asp-for="Post.Image" class="forupload" type="file" name="file">
<br>
<label asp-for="Post.CreatedDate" style="width:80px">Start Date</label>
<input asp-for="Post.CreatedDate" class="postinput" type="date" name="startDate"><br>
<span asp-validation-for="Post.CreatedDate"></span>
<label asp-for="Post.ExpirationDate" style="width: 80px">End Date</label>
<input asp-for="Post.ExpirationDate" class="postinput" type="date" name="endDate"><br>
<span asp-validation-for="Post.ExpirationDate"></span>
<label asp-for="Post.URL" style="width:45px">URL</label>
<input asp-for="Post.URL" class="postinput" type="text" placeholder="URL"><br>
<label asp-for="Post.Company.Name">Company</label>
<select asp-for="Post.CompanyId" asp-items="@Model.CompanyList" id="cat"></select>
<br>
<select asp-for="Post.SubcategoryId" asp-items="@Model.SubcategoryList">
<option value="">Select Subcategory</option>
</select>
<br>
<label asp-for="Post.Gifted" style="width:100px"></label>
<input asp-for="Post.Gifted" type="checkbox" name="gifted" class="special" id="forgift" />

<br />
<label asp-for="Post.SpecDiscount" style="width: 100px"></label>
<input asp-for="Post.SpecDiscount" type="checkbox" name="specDiscount" class="special" />

<br />
<button class="push" type="submit">Create</button>
</form>

Any suggestions?

How to target a public property of class T in a model Listvia asp-for ?

$
0
0

public class MyModelClass { public string propertyA { set; get; } public int propertyB { set; get; } }

My View uses a List<MyModelClass>  model to load a list of items for editing.

I am able to access the list of edited items through @Model[i].propertyA while iterating with i as the for loop indexer.

However I need to access the originally loaded items through the asp-for tag helper as follows:

<input type = "input" asp-for = "[@i].propertyA" />

This last line doesn't work. 

NOTE: when the model is not a List<MyModelClass> but just an instance of the MyModelClass, 

I simply use the following <input type = "input" asp-for = "propertyA" /> 

and it works without an issue.

so, how does one use asp-for to target a property of a class T when the Model is List<T> 

Help needed Image Processing

$
0
0

Hello Team,

I am working in Asp.net core 2.1 webAPI and i have a scenario like i get base64 string as input and i need to convert that to an image(jpeg) and need to store the image in different server (network path). can you please share me a code snippet to achieve this. Thanks in advance. 

Help Needed in Logging

$
0
0

Hi,

I have implemented logging for my asp.net core 2.1 web API using the following link. In this link example given to write to file system. This works fine. How to log in sqlserver level as well.  i need to write in both(File System and sqlserver). I tried to add this in JSON like the below. but it gives error. please help me write in both the places. Any sample will be highly appreciable.

http://anthonygiretti.com/2018/11/19/common-features-in-asp-net-core-2-1-webapi-logging/

"Serilog": {"MinimumLevel": "Information","WriteTo": [
      {"Name": "RollingFile","Args": {"pathFormat": "F:\\Log\\\\apilog-{Date}.txt","outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
        }
      }
    ],"WriteTo": [
      {"Name": "MSSqlServer","Args": {"connectionString": "<our connection string>","tableName": "Log"
        }
      }
    ],"Properties": {"Application": "Common feature in WebApi demo"
    }
  },

JWT token Help

$
0
0

Hello,

i am creating an API with asp.net core 2.1 and using JWT token authorization. My sample is working fine. i will deploying the API in microsoft azure cloud  load balancers.  assume API deployed in server A and Server B and if the token gets generated on server A has to be authorized on server B. because request May switch anytime b/w servers as they are load balancers. How does this work? What should i make it sot hat token can be authorized b/w servers. 


datetime issue

$
0
0

Hi

In my application a user adds a datetime of when they want something to be display, at present I get the users current time zone, and save the datetime in the database as utc after i have ajusted the time to represent utc.

However I have noticed that there is an issue,if the user has soemthing like daylight saving.The user puts in a time when they are not in day light saving but the start time is, the start time will be wrong.

How do I correct for this?

Any suggestions would be appriciated.

How to send a custom error message to ajax call from page hadler

$
0
0

am calling a  page handler method to get the customer details, if any error occurs in the server side then i need to throw a exception with the custom message  to the ajax call. Now the issue is am not getting back the custom error message i thrown it from page handler catch block.Below is the code i tried. Can anyone help me to solve this issue.

C# Handler method in my page mode

public async Task<JsonResult> OnGetCusomerDetailsAsync()
{
	try
	{
		return new JsonResult(new {data = await customerService.GetAllCutomersAsync()});
	}
	catch (Exception ex)
	{
		throw new Exception("Unable to get the Customer details", ex)
	}
}

Ajax call from JavaScript

      function getCustomerDetails() {
	ajax:
	{
		url: url,			
		type: "GET",
		success: function(result)  {
			result.data;
		}
		error: function (response, status, error) {			
			alert(response.statusText);
			alert(response.responseText);
		}
	},
      }

Here response.statusText is "Internal Server Error" and response.responseText is always null. How can i fetch the custom message that is thrown in my page-handler method

Mocking CreateAsync method of UserManager in Identity Core

$
0
0

I am trying to mock the CreateAsync() method of the userManager.

I am using ASP.Net Core 2.1.

I have mocked the FindByNameAsync() method.

I read elsewhere that in Identity 2.0 CreateAsync() method uses ValidateAsync methods.

  • I have mocked both.
  • I don't know how to give the userManager the mocked validator as a parameter.
  • I always get an error saying the constructor doesn't recognize the parameters.
  • I am getting Identity result as null even with the mocked user manager.

Test Case:

Mock<SurveyContext> mockdb =newMock<SurveyContext>();var mockValidator =newMock<IUserValidator<IdentityUser>>();
    mockValidator.Setup(x => x.ValidateAsync(It.IsIn<UserManager<IdentityUser>>(),It.IsAny<IdentityUser>())).Returns(Task.FromResult(IdentityResult.Success));var mockUserStore =newMock<IUserStore<IdentityUser>>();var mockUserRoleStore = mockUserStore.As<IUserRoleStore<IdentityUser>>();var mockUserManager =newMock<UserManager<IdentityUser>>(mockUserStore.Object,newMock<IOptions<IdentityOptions>>().Object,newMock<IPasswordHasher<IdentityUser>>().Object,newIUserValidator<IdentityUser>[0],newIPasswordValidator<IdentityUser>[0],newMock<ILookupNormalizer>().Object,newMock<IdentityErrorDescriber>().Object,newMock<IServiceProvider>().Object,newMock<ILogger<UserManager<IdentityUser>>>().Object);var mockRoleStore =newMock<IRoleStore<IdentityRole>>();var mockRoleManager =newMock<RoleManager<IdentityRole>>(
                 mockRoleStore.Object,null,null,null,null);

    mockdb.Setup(x => x.Add(addMember)).Returns((Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<MemberInfo>)null);
    mockdb.Setup(x => x.SaveChanges()).Returns(0);
    mockUserManager.Setup(x => x.CreateAsync(It.IsAny<IdentityUser>(),"password")).Returns(Task.FromResult(IdentityResult.Success));

    mockUserManager.Setup(x => x.FindByNameAsync(It.IsAny<string>())).Returns(Task.FromResult(It.IsAny<IdentityUser>()));


    mockUserManager.Setup(x => x.AddToRoleAsync(newIdentityUser(){UserName="username"},"password")).Returns(Task.FromResult(IdentityResult.Success));
    mockRoleManager.Setup(x => x.RoleExistsAsync("")).ReturnsAsync(true);
    mockRoleManager.Setup(x => x.CreateAsync(newIdentityRole())).Returns(Task.FromResult(IdentityResult.Success));

Whenever I use the use the createasync method contrary to expectation I am getting a null result.

What am I doing wrong?

ASP.NET Core SOAP and REST authentication

$
0
0

Hello
I am creating an API with the 2.2 kernel of asp.net.
I have two services (SOAP and REST) and the problem is that I want the SOAP service to be anonymous and the REST service be integrated windows

How to index dynamically inserted partial view with asp-for tag helpers?

$
0
0

I've scoured the internet today for a solution to this, but have not come up with one.

I have a form with an "add" button that allows me to insert rows of a partial view to add more items to my form.  The partial view uses a strongly-typed model and contains a set of inputs using asp-for tag helpers.  Example:

Model:

public class Product
{
  public int ProductId {get;set;}
  public string Name {get;set;}
  public int Quantity {get;set;}
}

Partial View:

@model MyApp.Models.Product

<input type="hidden" asp-for="ProductId"><input type="text" asp-for="Name"><input type="text" asp-for="Quantity">

Post-Action:
[HttpPost]
public ActionResult CreateProducts(List<Product> products)

I can successfully add multiple rows of my partial view, however I'm unable to add indexing to the them so they are grouped properly in the post-action.  Now I have seen someone use indexing when using a ViewModel (example: asp-for="Product[0].Name"), however my partial view does not use a multi-class viewmodel.  It's just the "Product" class.  So what is the proper way to add indexing to asp-for when you only have a single class?

Things I have tried that didn't work:

asp-for="Model[0].Name"
asp-for="Model.[0].Name"
asp-for="[0].Name"
asp-for="Name[0]"

Memory leak handling on dotnet core running on linux containers

$
0
0

I am trying to allocate memory to my application.

When there is memory overflow, there is no exception when I running my application on Linux container (based on 'microsoft/dotnet:2.2-runtime'),
but there is a 137 exception when running the docker, and when there is that exception the docker is killed and stop working.

my_docker_name exited with code 137

The above behaviour happens when the memory is almost at 100% usage, but not 100% usage.

Also, I realized that the memory allocation has different behaviour when running on dockers for linux. The memory is allocated not on new command, but is allocated when assigning that new to a value.

i.e. :


List<byte[]> Data;
int maxVal = 1024 * 1024 * 1024;
Data = new List<byte[]>();
for (int i = 0; i < 1000; i++)
{
Console.WriteLine("i:{0}", i);
Data.Add(new byte[maxVal]);
}

The code above running out of memory exception on windows, but not on linux-container. On linux that may happens only when assignment:

byte[] b = new byte[1024L * 1024 * 1024];
byte[] a = b; // cause the 137 error.

When I watch the memory by htop command, I see that the memory usage is almost 100%, but not 100% (also after the allocation).

I persume that there is some extra memory used to handle the kernel or the system, but I don't know how to handle or check that out.

The code is killed unexpectedly (After there is allocation of memory > 15G, while on the computer there is only 16G. Not catch in unhandled exception neither on try+catch).

How can I prevent that exception?

I am trying to check the available memory for dot net core.

When running the following:

Process p = Process.GetCurrentProcess();
long l = p.PagedMemorySize64;

Console.WriteLine("mem paged:{0}", l);
l = GC.GetTotalMemory(false);
Console.WriteLine("mem GC total:{0}", l);


In Window I get different results than Linux (unbuntu).

The first writeline returns on linux the result of 0 (on windows I get the real size).
The second line I got reasonable value, but I want to know the available memory (so I would know to handle the code before allocating the memroy).

The memory on the linux computer is 16G bytes (but I don't know to hard-coded this value - I want to calculate the available memory).

I have several projects running on dockers, so they participate the same memory.

It's not the same as for dotnet, i.e:

ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();

foreach (ManagementObject result in results)
{
Console.WriteLine("Total Visible Memory: {0}KB",
result["TotalVisibleMemorySize"]);
Console.WriteLine("Free Physical Memory: {0}KB",
result["FreePhysicalMemory"]);
Console.WriteLine("Total Virtual Memory: {0}KB",
result["TotalVirtualMemorySize"]);
Console.WriteLine("Free Virtual Memory: {0}KB",
result["FreeVirtualMemory"]);
}


The above is not compitable for C# core.

Also found a link: Get memory available on .NET core
but with no help - I got the zero result for 'PrivateMemorySize64'.

How can I prevent that 137 exception, and is there any best-practice for handle that one?

Waiting forwards for any help.

Thank you.

Menu ViewComponent - problem with getting Id to Subcategory URL

$
0
0

Hello,

I have another challenge that made me post here after many trials. 

I have dropdown menu that includes categories and subcategories. I extracted it to ViewComponent and got needed result of view. And action also worked for categories as it brought relevant category Id to the URL, but didn't work for subcategories though I did the same thing for them. Here is the details:

ViewModel

public class MenuModel
    {
        public int Id { get; set; }
        public Category Category { get; set; }
        public IEnumerable<Category> Categories { get; set; }
        public IEnumerable<Subcategory> Subcategories { get; set; }
        public string Action { get; set; }
        public string Controller { get; set; }
    }

Models

 public class Category
    {
        public Category()
        {
            Subcategories = new HashSet<Subcategory>();
        }

        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public ICollection<Subcategory> Subcategories { get; set; }
        public string Action { get; set; }
        public string Controller { get; set; }
    }

public class Subcategory
    {
        public Subcategory()
        {
            Posts = new HashSet<Post>();
        }

        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public Category Category { get; set; }
        public int CategoryId { get; set; }
        public ICollection<Post> Posts { get; set; }
        public string Action { get; set; }
        public string Controller { get; set; }
        public ICollection<CompanySubcategory> CompanySubcategories { get; set; }
    }

MenuViewComponent Model

 public class MenuViewComponent:ViewComponent
    {
        private readonly OfferDbContext _offerDbContext;

        public MenuViewComponent(OfferDbContext offerDbContext)
        {
            _offerDbContext = offerDbContext;
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            var menus = await _offerDbContext.Categories.Include(x => x.Subcategories)
                                             .Select(x => new MenuModel()
                                             {
                                                 Category = x,
                                                 Id = x.Id,
                                                 Action = x.Action,
                                                 Controller = x.Controller,
                                                 Subcategories = x.Subcategories.Select(y => new Subcategory()
                                                 {  
                                                     Name = y.Name,
                                                     Action = y.Action,
                                                     Controller = y.Controller
                                                 })
                                             }).ToListAsync();

            return View(menus);
        }
    }

Note: I didn't write Id = y.Id as there was no need, and even if written, it again doesn't work (tested).

View (Default.cshtml)

@using Foroffer.Models.ViewModels
@model IEnumerable<Foroffer.Models.ViewModels.MenuModel><div class="mobile"><div class="mobmenu"><button id="mobbtn"><i class="fas fa-bars"></i></button><ul class="mobcategory" id="catblock"><li><p>Kateqoriyalar</p></li>
            @foreach (MenuModel item in Model)
            {<li class="catlist"><a href="@Url.Action(item.Category.Controller, item.Category.Action, new {Id = item.Category.Id})">@item.Category.Name</a><ul class="mobsub">
                        @if(item.Subcategories != null && item.Subcategories.Count() > 0)
                        {
                            foreach (Subcategory submenu in item.Category.Subcategories)
                            {<li><a href="@Url.Action(submenu.Controller, submenu.Action, new {Id = submenu.Id})">@submenu.Name</a></li>
                            }
                        }</ul></li>
            }</ul></div>

Note that no error was reported. After index, when I click to enter relevant category from dropdown menu, it opens that category page as URL takes relevant controller, action and Id, but in subcategory, it only takes controller and action, I cannot get relevant subcategory Id to URL in order to open its page. I also tried to create another view model for subcategory and  used it in LINQ in ViewComponent action (InvokeAync), and no result again. 

Please, help me.


How can I exchange data with asp .net core?

$
0
0
I made a WPF programe yet.

And now I wanna to exchange data with the asp .net core for needs upload/download some data.

Such as getting user's information from the database, or creating a new account, changing the password of the account.

All are relate to the user's account system.

However, I only know how to make a webpage by asp .net core but I don't know how to exchange data with a desktop program.

I wanna not only a way to do it but also is safety enough.

How can I do it? Would you please help me? Thank you.

What was the need to create a separate middle ware for serving static files?

$
0
0

I am setting up a new ASP.NET core mvc project with EF Core. Now, When I read the docs for help in implementation, it always says to create a migration file (.cs) and then update the database with the help of that file. But, If have to create a separate class and then update the database instead of the usual update database commands, wouldn't it kill the purpose of setting of db easily using EF Core? I mean simply running update database command will also do the same thing but without the additional step of creating a migration file. So my question is, while setting up a project from the scratch, is it necessary to create a migration file of every single step i.e while initial creation of database with basic table and schemas? if so what are the advantages?

Multi-language options for dynamic content (from database) in ASP.NET Core MVC

$
0
0

HI guys,

I want to make my project in three languages, so the project will be multi-language. I've read about globalization & localization, but they are useful for static content such as menu names, datetime, and some other cultural things. I want to be able my CRUD operation in three languages, so that Admin will be able to create one post in different languages. And I don't need automatic translation as it doesn't translate well the sentence/paragraph based content. We will create them one-by-one, but I don't want to have different tables for them in database, but to make it so that resource-provider would work dynamically so that if I get content from database in default language by LINQ, it would be able to bind its other language variants. Thus, in click for ex. RU, the content would display the post description in Russian. Any good advice?

By the way, I've found one source (https://github.com/RickStrahl/Westwind.Globalization#installation-netcore )that explains this, but the way is long, I think there must be shorter way (for ex. choosing languanges in action using LINQ in relevant actions). I hope one of you found solution to such issue.

Installed on Win 10 IIS - getting [DefaultAntiforgery] error >> The antiforgery token could not be decrypted.

$
0
0

Hi All,

I have a Core 2.2 application that works without any issues on all development environments. I have to install the web application on a QA machine (Win 10 -- IIS) for testing, which I did. I am using the local machine and in the hosts file I have mapped the site to 127.0.0.1. On our development machines the installation works and all pages on the web app are function properly. However on the QA machine, the web application comes up but I get an error right away.

I think I need to install something else. I did install the Core hosting bundle, but I think I am missing something else. This is our Core application, and we are semi new to installing Core application on Windows IIS.

If anybody has any suggestions I would greatly appreciate it. 

Thanks!

BTW - This is the complete error that I am getting...

[2019-03-22 12:11:07,918] [ERROR] [ 6] [DefaultAntiforgery] An exception was thrown while deserializing the token.
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {6214cea0-77c2-4fa0-86a1-909aee39f8b6} was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
at Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)

Difference between ViewLocationFormats and PageViewLocationFormats

$
0
0

I am trying to change the paths used for page and partial views in a dotNet Core 2.2 project and found I can change the search paths with the code a bit down. There is both something called ViewLocationFormats and PageViewLocationFormats and I do not understand witch one is used when and why not one of them is enough.

After reading the documentation for ViewLocationFormats and PageViewLocationFormats and the description of the methods Intellisense shows I summarize them like this:

  • ViewLocationFormats is for "The locations of the views returned from controllers" and "Where RazorViewEngine will search for views"
  • PageViewLocationFormats is "Where RazorViewEngine will search for view (such as layouts and partials) when searched from the context of rendering a Razor Page"

I guessed from the above that ViewLocationFormat was for pages and PageViewLocationFormats was for shared/partials (now the naming sounds the wrong way around when I read it again...)

I added the below code to my Startup.cs file and Razor found my page file but not my partial file.

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddRazorOptions(razorOptions => {
                    // Custom path to page views
                    razorOptions.ViewLocationFormats.Clear();
                    razorOptions.ViewLocationFormats.Add("/Views/Pages/{1}/{0}.cshtml"); // Controller/Action
                    razorOptions.ViewLocationFormats.Add("(Views/Pages/{1}/{1}{0}.cshtml"); // Controller/ControllerAction

                    // Custom path to partials
                    razorOptions.PageViewLocationFormats.Clear();
                    razorOptions.PageViewLocationFormats.Add("/Views/Partials/{0}.cshtml"); // PartialName
                });

Code used for the partial inside the page view file:

<partial name="MyPartial" model="dataForPartial" />

This gave me the below error:

An unhandled exception occurred while processing the request.
InvalidOperationException: The partial view 'MyPartial' was not found. The following locations were searched:
/Views/Pages/MyPage/MyPartial.cshtml
(Views/Pages/MyPage/MyPageMyPartial.cshtml
Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)

I tried put all three paths in both of them and it would work but I would like to know how they differ. One of them sounds like its used when "return View();" is called in a controller and the other one when a partial is referenced in a view file but that appears to not be correct.

Viewing all 9386 articles
Browse latest View live