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

How to pass value from text item to a partial view?

$
0
0

I've some value returned in a text item:

<input type="text" id="case_id" />

it is returned correctly by this ajax code:

$("#form").submit(function (e) {
            e.preventDefault();$('#myAlert').hide();$.ajax({
                type: "POST",
                url: '/Sex/Create/',
                data: $('#form').serialize(),
                success: function (data) {
                    document.getElementById("case_id").value = data;$('#myAlert').show('fade');
                    setTimeout(function () {$('#myAlert').hide('fade');
                    }, 3000);

                },
                error: function (xhr, text, error) {
                    alert('Error: ' + error);
                }
            });            
        });

Now  I'm calling a parial view in this view:

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

How to pass the previos returned value in a text item in the partial (Sto/Create)? (may assign the value in ViewBag)


Default dateTime format for all aplication

$
0
0
 services.Configure<RequestLocalizationOptions>(opt =>
            {
                opt.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-GB");
                opt.DefaultRequestCulture.Culture.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
                opt.DefaultRequestCulture.Culture.DateTimeFormat.DateSeparator = ".";
            });


Hi

I try to setup default dateTime format in Startup. cs with code, but Datetime shown like this 14/03/2019

How I can resolve this problem?

Visual Studio Code IDE, cannot launch browser, access denied even when run under admin privileges?

$
0
0

Help

Hosting environment: Development
Content root path: C:\Users\dan\OneDrive\dan\WEBA
Launching browser (cmd.exe /C start http://localhost:50136)
WARNING: Launching browser failed. Error = Access is denied
Now listening on: http://localhost:50136

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

$
0
0
I'v been reading about .net core for a while when I read about request and middle wares. I can't seem to wrap my head around the need for app.UseStaticFiles() middle ware because no matter what application we create, we will need to include something or the other static files so there will always be a need to write app.UseStaticFiles() middle ware which doesn't make sense to register every time in our pipeline. So, can anyone clear my doubts here.

How do I know if Kestrel is running in windows environment?

$
0
0
I read that one of the reasons why asp.net core is cross platform is because of kestrel server and it's ability to serve requests in linux environment(correct me if I am wrong here). But what happens if I am on Windows environment and am running my project. While running or debugging, I can clearly see IIS Express option written in the top menu on debug button which presumably tells me that requests are now been served on IIS Express so where does the role of Kestrel server come into picture and what is it doing in background if IIS is running?

How to read Azure SQL DB connection strings from appsettings..json file using .NET Core 2.2 Console Application

$
0
0

I'm creating a console application using .net core 2.2 with EF Core 2.2.2. Here I'm struggling to maintain Azure SQL Server connection strings dynamically based on the Environment Variable i.e Dev, stage and Prod environment. The connection strings are maintained separate appsettings.(Environment).json files. So I need to get the connection string from the appsetting.(Environment).json file and pass it to the optionsBuilder.UseSqlServer("Azure SQL DB Connection") function when I run my console application. Please help me to resolve this issue.

appsettings.Dev.json

{ "Database": 
  { "ConnectionString": "Server=xxxxxxxxxx.database.windows.net,1433;Database=qualcontract;User Id=xxxxxx;Password=xxxxxxxx" 
  } 
}

I have not seen like this example in MS document.

Thanks in advance,
Parthi Karnan

Not rendering HTML for Chart Reports in LocalReport

$
0
0

Hi,

I have try to export report in Html using below code but it is not rendering properly.

.rdl file contains chart

I have attached screen shot of Html

Highly appreciate if you can help on us to resolve this issue.

thanks

PlatForm: ASP.NET Core

public string _reportPath = @"..\\RenderReportAPI\\employeeChart.rdl";

string mimtype ="";
int extension = 1;

               LocalReport localReport = new LocalReport(_reportPath);

            _dataSourceName = "DataSet1";
            _dataSourceList = Employee.GetEmployees();                                   
            localReport.AddDataSource(_dataSourceName, _dataSourceList);

           

            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            var result = localReport.Execute(RenderType.Html, extension, null, findString: mimtype);

Dynamic reports in MVC Core 2.0

$
0
0

All,

I need to implement reports in MVC Core 2.0. The reports need to be dynamic, in the sense, the user will select what columns need to be in the report and on button click, the report should get generated with the selected columns. I came across a nuget package - "Microsoft.Report.Viewer" but not getting any samples or pointers which i can refer. My understanding is that there should be a way (may be a service), i can configure the ReportViewer control (without generating any .rdlc) file and display the report under ReportViewer control. I do not know how everything should fall

Has someone done this kind of thing before? Any examples please?

Or any other reporting tool that you may suggest so i can accomplish this task?

thanks in advance, please suggest!


is it possible to access database in an Authorization Filter?

$
0
0

hi,

I take database via constructor in classes and in action filters after the action execution I use resultContext.HttpContext.RequestServices.GetService<T>(); and then via a service I can access the database. does anyone knows how I can use database in Authorization Filter and is it a right approach to do so?

I can create an object from datacontext but I don't know what should the DbContextOptions be.

Thanks in advance

AspNetCore Reporting

$
0
0

I am trying to execute the report in .net core API project

here is the code:

List <MileageItem> dsMileageItems = new List<MileageItem>();
MileageItem newItem = new MileageItem();
newItem.CreatedAt = DateTime.Now;
newItem.EntryTime = DateTime.Now;
newItem.Mileage = 100000;
newItem.Note = "NewNote";
dsMileageItems.Add(newItem);

LocalReport localReport = new LocalReport("TestReport1.rdlc");
localReport.AddDataSource("DataSource1", dsMileageItems);

var result = localReport.Execute(RenderType.Pdf, extension);

byte[] bytes = result.MainStream;

Stream stream = new MemoryStream(bytes);
stream.Position = 0;
return File(stream, "application/pdf", "Report.pdf");

But I am getting the following error:

An unhandled exception has occurred while executing the request.
AspNetCore.Reporting.LocalProcessingException: An error occurred during local report processing.;The definition of the report 'TestReport1.rdlc' is invalid.
An unexpected error occurred in Report Processing.
Unable to load shared library 'kernel32.dll' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(libkernel32.dll, 1): image not found ---> AspNetCore.Reporting.DefinitionInvalidException: The definition of the report 'TestReport1.rdlc' is invalid.
An unexpected error occurred in Report Processing.
Unable to load shared library 'kernel32.dll' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(libkernel32.dll, 1): image not found ---> AspNetCore.ReportingServices.ReportProcessing.ReportProcessingException: An unexpected error occurred in Report Processing.

Any help would be appreciated.

RDLC is created in Visual Studio 2017 (as part of Windows Application project 4.6.1)
RDLC is connecting to SQL Server Dataset.

Based on the above I presumed that this dataset could be represented by List<Object> in .net core.
Project is running in Visual Studio on Mac

How can I open a pdf file by not showing link and/or with autherisation

$
0
0

Hi all I want to let the user to open his uploaded pdf file like this

www.mywebsite.com/5874.pdf

however I only want user is able to open it, (and probably not showing the file name in url) how can I do this?

thank you

Generate and download PDFs using Razor Pages.

$
0
0
Hello,

i made a mistake, i decided to use Razor Pages for a project one year ago.

Now i'm back working on this project because the customer wants new features, such as being able to generate PDF reports: i wanted to generate PDFs using html code, so i can easily create layouts and use templates which get injected by data and then downloaded as PDF files.

There are al ot of libraries, all of them don't (or are not meant) to work using Razor Pages: all of them have been created with MVC in mind.

Is there a way to easily implement PDF generation using razor pages without having to reinvent the wheel?

Thank you.

Stuff i tried:

http://nyveldt.com/blog/page/razorpdf

https://github.com/DesignLiquido/RazorPDF2

https://github.com/aaxelm/Rotativa.NetCore

PS. I'm using . NET Core 2.2

core2.2 ajax calls

$
0
0

Hi I try to make an ajax call to my razor.cshtml.cs file.

my jquery is:

$.ajax({
                type: "post",
                url: "/RoosterMember/SetDepartment/Edit",
                dataType: 'JSON',
                data: {
                    OrgUserId: id,
                    OrgDepartmentId: Depid,
                    OrgStartDate: datum,
                    NewDepartmentId: $('#ListDiv').jqxDropDownList('valueMember'),
                    NewStartDate: $('#SetDepEditCancel').jqxDateTimeInput('value')
                },
                success: function (xhr) {
                    alert('Record wad succsesfull edited!');
                },
                error: function (xhr) {
                    alert('Edit operation failed!');
                }

My c# in the cshtml.cs file is:

public class EditModel
{
public string OrgUserId { get; set; }
public int OrgDepartmentId { get; set; }
public DateTime OrgStartDate { get; set; }
public int NewDepartmentId { get; set; }
public DateTime NewStartDate { get; set; }
}

public IActionResult OnPostEdit(EditModel model) { try { //find original record UserDepartement ud = (from x in _DB.UserDepartements where x.DepartementId == model.OrgDepartmentId && x.UserId == model.OrgUserId && x.StartDate == model.OrgStartDate select x).FirstOrDefault(); //Edit this record if (ud.DepartementId != model.NewDepartmentId) { ud.DepartementId = model.NewDepartmentId; } if (ud.StartDate != model.NewStartDate) { ud.StartDate = model.NewStartDate; } //return to DB. _DB.SaveChangesAsync(); //Notify the client that operation was succesfull. return Content("ok"); } catch { //Notify the client that operation was not succesfull. return Content("Fail"); } }

I can see from the (f12) debugger that a call is made to the page/edit function but the http result stays pending.

if I put a breakpoint in my Edit function but it is never called. I have try to make the ajax call as simple as possible, without any model and data. but I can not reach the server function from my ajax call.

What am I doing wrong?

Cascading dropdownlist using SelectList class and JQuery (Ajax)

$
0
0

Hi guys,

I have problem with Cascading dropdown list. After selecting any category, I need to get relevant subcategories in the second dropdown. Seems easy, but doesn't work with SelectList class which I used. After selecting any category, seems it doen't recognize Id, and no subcategory comes to select.

Controller

[HttpGet]
public async Task<IActionResult> Postadd()
{
AdminPostModel postModel = new AdminPostModel();
postModel.Categories = await _offerDbContext.Categories.ToListAsync();

ViewBag.Categories = postModel.Categories;

return View(postModel);
}

public JsonResult getSubList(int Id)
{
List<Subcategory> list = new List<Subcategory>();
list =_offerDbContext.Subcategories.Where(a => a.CategoryId == Id).ToList();

return Json(new SelectList(list, "Id", "Name"));
}

View

@model Foroffer.Models.ViewModels.AdminPostModel
@{
Layout = "AdminLayout";


}<form method="post" asp-action="Postadd" asp-controller="Post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly"></div>

<label asp-for="Post.Subcategory.Category.Name">Category</label>
<select id="CatId" name="CatList" asp-for="Category.Id" asp-items ="@(new SelectList(ViewBag.Categories, "Id", "Name"))" >
</select>
<br />
<label asp-for="Post.Subcategory.Name">Subcategory</label>
<select id="SubId" name="SubList" asp-for="Post.SubcategoryId" asp-items="@(new SelectList(String.Empty, "Id", "Name"))">
<option value="">Select Subcategory</option>
</select>
<br>
<button class="push" type="submit">Create</button>
</form>

<script>
$(document).ready(function () {
$("#CatId").on("change", function () {
$list = $("#SubId");
$.ajax({
url: "/getSubList",
type: "GET",
data: { id: $("#CatId").val() }, //id of the state which is used to extract cities
traditional: true,
success: function (result) {
$list.empty();
$.each(result, function (i, item) {
$list.append('<option value="' + item["Id"] + '"> ' + item["Name"] + ' </option>');
});
},
error: function () {
alert("Something went wrong call the police");
}
});
});
});

</script>

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; }
}

Please, help ASAP

Asp.net core 2.1 and Rabbitmq

$
0
0

Hi there,

I am working on a asp.net core 2.1 microservices with Rabbitmq, I just need to hook up this in my asp.net core web api in Startup.cs, any idea how that could be done?

I am thinking something like a listener listening to the queue, I googled it and did not find a good one that I can easily follow. I found this https://github.com/devmentors/DNC-DShop.Common/tree/master/src/DShop.Common/RabbitMq, it is complicated and involved a lot of things that I do not need, and this one as well, https://stackoverflow.com/questions/43609345/setup-rabbitmq-consumer-in-asp-net-core-application, it is very brief, not sure how that really can be done property.

Anyone has any good way or demo, or some useful links? 

Thanks in advance.

Bob


How to get fields exist on table by passing table name by using asp.net core 2.1 ?

$
0
0

How to get fields exist on table by passing table name ?

suppose I have table name Employee on SQL server 2012

and this is fields of Employee Table EmployeeCode,EmployeeName,,..etc

How to make function pass to it table name and it will retrieve fields or columns as 

EmployeeCode,

EmployeeName

I work on web API core project with angular 7 

structure of function as below

public List<string> GetColumnNames(string tablename)
{
}



How to change the default hosting model from OutOfProcess to InProcess in ASP.NET Core application?

$
0
0

I created a new asp.net core MVC project and when I ran it I realised that it is running in OutOfProcess hosting model but I want it to run in InProcess hosting model.

I tried editing csproj file and adding <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> but that didn't work out.

Also, there is no option to select hosting model in my debug profile.

how to pass List from one action to another action in the sames controller. Please help

$
0
0

Hi

My controller name is Report. There is two action 1. ReportCriteria  2.CallReport

In ReportCriteria Action

public IActionResult AttendanceReportCriteria(ReportViewModel report)
        {
           List<AttendanceLogModel> log = new List<AttendanceLogModel>();
            log = ReportService.GetEmployeeAttendanceReport(String.Join(",", 
             report.Depot), String.Join(",", report.Department), String.Join(",", 
             report.Employee), fromDate, toDate, connectionSettings);

            //TempData["log"] = log;
            return RedirectToAction("AttendanceReport",log);  
          }

public IActionResult AttendanceReport(List<AttendanceLogModel> log )  // The value is not passing here
        {
            // List<AttendanceLogModel> log = TempData["log"] as List<AttendanceLogModel>;
            ViewBag.AttendanceLogs = log;
            return View();
        }

Here I am trying to pass the  the list   log from ReportCriteria to another action AttendanceReport. Please can you suggest a suitable code to pass the list . 

With Thanks

Pol

newbie question about a side panel

$
0
0

I am using bootstrap, Razor and Razor pages in Visual Studio.  I also am learning Javascript, expecting to use it for the site later.  

I would like to add a sidebar or panel to about ten of the twenty pages.  As far as I know, this side panel will have the same information on it, regardless of the other portion of the page being shown.  It will be a list of words, a drop down selection list, and a small text area near the bottom.

I started out by changing my container to "container-fluid" which requires me to undo this on the half of the pages that don't have a sidepanel.

For the others I don't know any other way to do this except to create a partial view, and send the information for display to it on each and every page load.

I am already running into troubles.  For example, when I attempted to make the side panel col-sm-3 that works as expected, but then when I added a "style ="margin-right:10px" it completely wiped out the panel.  

Also, if possible I would like the list of words to stay in sight, even if someone scrolls down the page a ways.

Is there a better way than a partial view? (which does not keep the list in view)

routing and link in view

$
0
0

<a asp-area="" asp-controller="home" asp-action="ProductDetail" asp-route-id="@item.Id" asp-route-title=@item.title asp-route-category=@item.category> click me</a>

I have this View1

I want the user to click on a link in the view to transfer a piece of information to the method's action. But do not consider this information in rooting.for example id and title is in routing but category isn't.

Viewing all 9386 articles
Browse latest View live


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