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

Razor Page loading from CHTML.cs code page

$
0
0

My code page  has this 


public List<IPVmodels.ConfigListData> ListConfigs2= new List<IPVmodels.ConfigListData>(); // also tried get;set but still nothing
public List<string> TestList = new List<string> { "a", "b", "cat" };

public void OnGet()
{
IPV2.Repository.IPVData ipData = new IPVData(_configuration);

List<IPVmodels.ConfigListData> ListConfigs2 = ipData.Get....();  // uses Dapper to load this list
}

The ListConfigs2 object is loaded with 17 items  but on the .CHTML @Model.ListConfigs2.Count = 0  and TestList is 3.

When I put a break point in the cs file at end of OnGet() both ListConfigs2 and TestList are populated, but on  the CHTML ( view ) the class properties are known but the content on the ListConfigs2 is empty as if never populated.     What needs to change to make  the data visible on the page ?

Thanks 


Angular JS in Visual Studio

$
0
0

Hello everybody,

I am hesitant about what forum to choose, I want to practice Angular JS in a Visual Studio project, with Visual Studio Community 2017, version 15.9.4.

As I saw there is an Angular JS project type that uses Node.js, it seems not to be too false to ask that in the ASP.Net Core section.

I had to derive the dbContext to define an options object, I hope I did not miss that part.

Well anyway, the solution is generated, but the results web page shows quite a collection of errors, I presume the most significant is this one :

InvalidOperationException: The NPM script 'start' exited without indicating that the Angular CLI was listening for requests. 
The error output was: 'ng' is not recognized as an intern or extern command, or a command file. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! ModCoreAng01@0.0.0 start: `ng serve "--port" "52788"` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the ModCoreAng01@0.0.0 start script. npm ERR!

(I translated from French the part about ng not recognized as a command).

Well, despite the fact that the project type is dedicated to AngularJS, am I supposed to declare it somewhere ?

Somebody solved that problem by installing Node.js, so I have to precise that I installed it and restarted the machine.

Also, somewhere I had to remove " -- --app=ssr --output-hashing=media", but that did not solve the problem (and I have to recognize I did not realize why these clauses are put in the default file whereas it seems better not to put them).

Well, is anybody able to help me ?

Do you think I should provide the whole output page ? Or give any more precisions ?

HttpContext.Request

$
0
0

I need some clarification please!

I used to use HttpContext.Request.Browser.IsMobileDevice in ASP.NETMVC5 but I've recently moved to .Net Core 2 and I just realized that Request.Browser is not available anymore, but instead I could use something like HttpContext.Request.Headers["User-Agent"]

So my question is, am I missing something that why I could not get the Request.Browser.IsMobileDevice or it is something that is not in .Net Core anymore?

Thank you.

Configure Active Directory group and Check if user belongs to that AD group in .Net CORE 2.2

$
0
0

Hi ,

     I'm new to the .net core and trying to authenticate only users from a Active Directory group to access the application. I have everything set up to allow only the ADGroup but the application is not able to read the appsettings not identifying the group and denying the access to the windows- Active directory users. 

appsettings.json

{"Logging": {"LogLevel": {"Default": "Debug","System": "Information","Microsoft": "Information"
    }
  },"AllowedHosts": "*", "SecuritySettings": {"ADGroup": "LSNET\\ADCAdmin"  // here is my AD group 
  }

}

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);
               

            services.Configure<IISServerOptions>(options =>
            {
                options.AutomaticAuthentication = true;
            });

            services.Configure<IISOptions>(options =>
            {
                options.ForwardClientCertificate = false;
            });


            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddJsonOptions(options =>
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver());


            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();

                config.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("ADRoleOnly", policy => policy.RequireRole(Configuration["SecuritySettings:ADGroup"]));
            });


            // Add Kendo UI services to the services container
            services.AddKendo();
            services.AddAutoMapper();           

        }
		

ADController.cs

[Authorize(Policy = "ADRoleOnly")]
    public class ADController : Controller
    {
       //Authenticate only users from the ADGroup.
    }

 Thank you

How to Export datatable into csv format

$
0
0

I  am trying to export the   datatable into csv format . When Click the Export Excel button ,  should be saved into download folder as a csv format. Please can you help me how can I export  the datatable

<div class="table-responsive"><table id="empview"   class="display nowrap" cellspacing="0" style='font-size:80%'><thead class="thead-light"><tr><th>Code</th><th>FirstName</th><th>LastName </th><th>Salary</th></tr>

 @foreach (EmpModel  _empmodel in @ViewBag.Empview)
                                    {
                                        <tr><td style="max-width:500px;overflow:hidden; white-space:nowrap">@_empmodel .Code</td><td>@_empmodel.FirstName</td><td>@_empmodel.LastName</td><td>@_empmodel.Salary </td></tr></table></div><div><button type="submit" class="btn btn-primary  col-sm-2">Export Excel</button></div>$(document).ready(function () {
        var table = $('#empview').DataTable({
            scrollY: "300px",
            scrollX: true,
            scrollCollapse: false,
            paging: false,
            fixedColumns: {
                leftColumns: 1

            }
        });

ASP.Net Core 2.2 and Angular 6 deployment in Windows Container

$
0
0

Is it technical possible to deploy Angular 6 with ASP.Net Core 2.2 in Windows Container?

If yes, what is the docker file configuration and  code changes needs to be done?

Difficulty in running Asp.net core web app in solution that previously contained asp.net apps

$
0
0

Dear All,

I have a solution that contains loasd of my asp.net project as a matter of fact I started building this solution with VS2013 before asp.net core came out. But since I have vs 2017. I copied the solution to the VS 2017 project folder. Right now I would to start a new project which suppose to be a asp.net core web application. But I usually have difficulties adding .net core project to this solution. I have added one and I can not run the web application. each time I try IIS just tends to freeze. I ended up with this message below

<div class="content-container">

HTTP Error 502.3 - Bad Gateway

The specified CGI application encountered an error and the server terminated the process.

</div> <div class="content-container">

Most likely causes:

  • The CGI application did not return a valid set of HTTP errors.
  • A server acting as a proxy or gateway was unable to process the request due to an error in a parent gateway.
</div> <div class="content-container">

Things you can try:

  • Use DebugDiag to troubleshoot the CGI application.
  • Determine if a proxy or gateway is responsible for this error.
</div> <div class="content-container">

Detailed Error Information:

<div id="details-left">
Module   AspNetCoreModule
Notification   ExecuteRequestHandler
Handler   aspNetCore
Error Code   0x80072ee2
</div> <div id="details-right"></div> <div>Please what do I do to ensure that I can have my asp.net core project within this solution.   Please  I would appreciate swift response cos the client is already on my case.</div> <div></div> <div>Thanks alot.</div>
</div>

No data saved in the partial view!

$
0
0

Hi

I'm trying to save data updated on the partial view called in Edit action.

I have these models:

Nz Class:

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

namespace NozCoreWebApp5.Models
{
    public partial class Nz
    {
        public Nz()
        {
            Mkh = new HashSet<Mkh>();
        }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#########}")]
        public decimal TxtId { get; set; }
        public int Sn { get; set; }
        public string FullName { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime? BirthDate { get; set; }
public int SexCode { get; set; } public string InsertUser { get; set; } [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] public DateTime InsertDate { get; set; } public ICollection<Mkh> Mkh { get; set; } } }

Mkh Class: (child for Nz)

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

namespace NozCoreWebApp5.Models
{
    public partial class Mkh
    {
        public int Sn { get; set; }
        public decimal TxtId { get; set; }
        public int MkhCode { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime MkhDate { get; set; }
        public int Days { get; set; }
        public string Notes { get; set; }
        public string InsertUser { get; set; }
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime InsertDate { get; set; }


        public MkhType MkhCodeNavigation { get; set; }
        public Nz Txt { get; set; }
    }
}

MkhType Calss: (Parent of Mkh)

using System;
using System.Collections.Generic;

namespace NozCoreWebApp5.Models
{
    public partial class MkhType
    {
        public MkhType()
        {
            Mkh = new HashSet<Mkh>();
        }

        public int MkhCode { get; set; }
        public string MkhName { get; set; }
        public string InsertUser { get; set; }
        public DateTime InsertDate { get; set; }

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

and I have this context:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace NozCoreWebApp5.Models
{
    public partial class NozContext : DbContext
    {
        public NozContext()
        {
        }

        public NozContext(DbContextOptions<NozContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Mkh> Mkh { get; set; }
        public virtual DbSet<MkhType> MkhType { get; set; }
        public virtual DbSet<Nz> Nz { get; set; }
        public virtual DbSet<Sex> Sex { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer("Server=My-PC\\SQLEXPRESS;Database=Noz;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<Mkh>(entity =>
            {
                entity.HasKey(e => e.Sn);

                entity.ToTable("Mkh");

                entity.Property(e => e.Sn).HasColumnName("sn");

                entity.Property(e => e.Days).HasColumnName("days");

                entity.Property(e => e.InsertDate)
                    .HasColumnName("insert_date")
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())");

                entity.Property(e => e.InsertUser)
                    .IsRequired()
                    .HasColumnName("insert_user")
                    .HasMaxLength(20)
                    .HasDefaultValueSql("(N'any')");

                entity.Property(e => e.MkhCode).HasColumnName("Mkh_code");

                entity.Property(e => e.MkhDate)
                    .HasColumnName("Mkh_date")
                    .HasColumnType("date");

                entity.Property(e => e.Notes).HasColumnName("notes");

                entity.Property(e => e.TxtId)
                    .HasColumnName("txt_id")
                    .HasColumnType("numeric(9, 0)");

                entity.HasOne(d => d.MkhCodeNavigation)
                    .WithMany(p => p.Mkh)
                    .HasForeignKey(d => d.MkhCode)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_Mkh_Mkh_type");

                entity.HasOne(d => d.Txt)
                    .WithMany(p => p.Mkh)
                    .HasForeignKey(d => d.TxtId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_Mkh_Nz");
            });

            modelBuilder.Entity<MkhType>(entity =>
            {
                entity.HasKey(e => e.MkhCode);

                entity.ToTable("Mkh_type");

                entity.Property(e => e.MkhCode).HasColumnName("Mkh_code");

                entity.Property(e => e.InsertDate)
                    .HasColumnName("insert_date")
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())");

                entity.Property(e => e.InsertUser)
                    .IsRequired()
                    .HasColumnName("insert_user")
                    .HasMaxLength(20)
                    .HasDefaultValueSql("(N'any')");

                entity.Property(e => e.MkhName)
                    .IsRequired()
                    .HasColumnName("Mkh_name")
                    .HasMaxLength(50);
            });

            modelBuilder.Entity<Nz>(entity =>
            {
                entity.HasKey(e => e.TxtId);

                entity.ToTable("Nz");

                entity.Property(e => e.TxtId)
                    .HasColumnName("txt_id")
                    .HasColumnType("numeric(9, 0)");

                entity.Property(e => e.BirthDate)
                    .HasColumnName("birth_date")
                    .HasColumnType("date");


                entity.Property(e => e.InsertDate)
                    .HasColumnName("insert_date")
                    .HasColumnType("datetime")
                    .HasDefaultValueSql("(getdate())");

                entity.Property(e => e.InsertUser)
                    .IsRequired()
                    .HasColumnName("insert_user")
                    .HasMaxLength(20)
                    .HasDefaultValueSql("(N'any')");

                entity.Property(e => e.SexCode).HasColumnName("sex_code");

                entity.Property(e => e.Sn)
                    .HasColumnName("sn")
                    .ValueGeneratedOnAdd();

                entity.HasOne(d => d.SexCodeNavigation)
                    .WithMany(p => p.Nz)
                    .HasForeignKey(d => d.SexCode)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_Nz_sex");
            });

            modelBuilder.Entity<Sex>(entity =>
            {
                entity.HasKey(e => e.SexCode);

                entity.ToTable("sex");

                entity.Property(e => e.SexCode).HasColumnName("sex_code");

                entity.Property(e => e.SexName)
                    .IsRequired()
                    .HasColumnName("sex_name")
                    .HasMaxLength(10);
            });

            modelBuilder.Entity<Nz>()
            .HasAlternateKey(x => x.Sn).HasName("IX_Sn");
        }
    }
}

and the NzController actions:

    public class NzController : Controller
    {
        private readonly NozContext _context;

        public NzController(NozContext context)
        {
            _context = context;
        }
// ........ Some Code here .............
public async Task<IActionResult> Edit(decimal? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            //var Nz = await _context.Nz.FindAsync(id);
            var Nz = await _context.Nz
                         .Include(n => n.Mkh)
                         .ThenInclude(m => m.MkhCodeNavigation)
                         .FirstOrDefaultAsync(n => n.TxtId == id.Value);
            if (Nz == null)
            {
                return NotFound();
            }
            ViewData["SexCode"] = new SelectList(_context.Sex, "SexCode", "SexName", Nz.SexCode);
            return View(Nz);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(decimal id, [Bind("TxtId,Sn,FullName,BirthDate,SexCode,InsertUser,InsertDate")] Nz Nz)
        {
            if (id != Nz.TxtId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var Edited = new Nz()
                    {
                        TxtId = Nz.TxtId,
                        BirthDate = Nz.BirthDate,
                        InsertDate = Nz.InsertDate,
                        InsertUser = Nz.InsertUser,
                        FullName = Nz.FullName,
                        SexCode = Nz.SexCode,
                        Mkh = Nz.Mkh.Where(m => m.TxtId == Nz.TxtId).ToList(),
                    };
                    _context.Update(Edited);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!NzExists(Nz.TxtId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["SexCode"] = new SelectList(_context.Sex, "SexCode", "SexName", Nz.SexCode);
            return View(Nz);
        }

the partial view 'EditNz' in Mkh controller:

@model IEnumerable<Mkh><h4>MkhTbl</h4><hr /><table class="table"><thead><tr><th>
                    Date</th><th>
                    Days</th><th>
                    Notes</th><th>
                    Mkh Type</th><th></th></tr></thead><tbody>
            @foreach (var item in Model)
            {<tr><td> 
                        @Html.EditorFor(modelItem => item.MkhDate)</td><td>
                        @Html.EditorFor(modelItem => item.Days)</td><td>
                        @Html.EditorFor(modelItem => item.Notes)</td><td>
                        @Html.EditorFor(modelItem => item.MkhCodeNavigation.MkhName)</td></tr>
            }</tbody></table>

    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

and the calling of the previous partial in Edit view in NzController:

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

Now when I press save button (submit) no data is saved for the partial one like days! Why? and How to solve please?

and How to return Select with returned values from MkhType? (using MkhCodeNavigation I think)


how can I change the checkbox button into dropdown listbox

$
0
0

Hi

I am trying to change the change the check box into radio button but not working please can you help how to make my code   into radio button rather than check box. Please can you help it would be very appreciated

<div class="col-md-6"><label class="control-label control-label-left   yellow_text" for="field1">Depot*</label><select id="dropdownDepot" class="form-control" multiple asp-for="Depot" asp-items="@ViewBag.UserDepots" data-role="select"></select></div>$('#dropdownDepot').multiselect({
        columns: 2,
        placeholder: 'Select Depot',
        includeSelectAllOption: true,
        maxHeight: 300
    });

How can I implement naps2 with commandline in my .net core web app

$
0
0

Hi all,

the software which is called naps2 has great implementation to scan a document to pdf.

I want to use it for client to scan and upload documents to my .net core web app server.

Could you tell me how can I implement it via cmd (naps2 provides cmd commands)

Thank you.

Replacing Datagrid view with datatables with lookups on razor pages

$
0
0

I am in the process of moving a web app from frameworks to core so it can be run on a Linux host. By following the ‘Getting Started with EF Core on ASP.NET Core with an Existing Database’ (https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db?view=aspnetcore-2.2)

I have been able to display the data on the razor page.

In the data rows there are 2 columns with data id’s that I would like to display the corresponding name for the data id, so humans can understand the data. The datagrid view enable lookups on the columns. How do I do this with EF and data tables?

I have formatted the data on the razor page by using the tools from mdbootstap.net.

How can I show the name for the data id in a data table in a razor page?

Problem occur when hosting ASP.NET core 2.1 project locally on computer?

$
0
0

I have save my asp project at location

C:\inetpub\wwwroot\ourtechroom
Then when I runs
localhost/ourtechroom

on browser I got below error.

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Detailed Error Information:
Module	   IIS Web Core
Notification	   BeginRequest
Handler	   Not yet determined
Error Code	   0x8007000d
Config Error	   
Config File	   \\?\C:\inetpub\wwwroot\ourtechroom\web.config
Requested URL	   http://localhost:80/ourtechroom
Physical Path	   C:\inetpub\wwwroot\ourtechroom
Logon Method	   Not yet determined
Logon User	   Not yet determined



Help Me I am in big trouble?

My web.config looks like this:

<?xmlversion="1.0"encoding="utf-8"?><configuration><locationpath="."inheritInChildApplications="false"><system.webServer><handlers><addname="aspNetCore"path="*"verb="*"modules="AspNetCoreModule"resourceType="Unspecified"/></handlers><aspNetCoreprocessPath="dotnet"arguments=".\OurTechRoom.dll"stdoutLogEnabled="false"stdoutLogFile=".\logs\stdout"/></system.webServer></location></configuration><!--ProjectGuid: a4eff15f-7cc7-44e3-9939-904c7255382d-->



What I have tried:

I have tried by just creating index.html inside wwwroot folder of Inetpub then i am able to access this file via localhost/index.html but when trying to access above url ie

http://localhost/ourtechroom[^]

I am getting above error.

I have also try resolve the problem by the solution enlisted in below sites:

<div class="pre-action-link" id="premain103698">Hide   Copy Code</div>
https://support.microsoft.com/en-gb/help/942055/http-error-500-19-error-when-you-open-an-iis-7-0-webpage

How to detect a new session in Core 2.1?

$
0
0

How do I detect that a session is new?

I have kludged something together using cookies but there has to be a better way.  Under ASP.NET 4.x I was able to ask the HttpContext.IsSessionNew  (or something similar).  How does one do this in Core 2.1?

Why ASP.NET Core 2.2 MVC project require 2 copies of font file (.otf)? !!!HELP!!!

$
0
0

I am having a very strange problem, I am developing a simple ASP.Net 2.2 MVC Project here. I need to use custom font and I have a .otf file. However I am having a wired problem here. As you can see in following screencast, I am using following CSS declare the usage of the font

And here is my folder structure and files of the project:

As I highlighted in screen cast I have to have the one copy of font file in wwwroot folder and in project root directory in order for the font to be found and correctly shows on the webpage, delete either of those two, the webpage will not show correct file. By the way I have static file enabled in the program:I have tried to change the path of the otf file in css to point to the font file under wwwroot so I can have only one copy of font file, but it does not work.

This problem is not a big deal for me now. Having two copy of font file doesn't really hurt anything. I am just wondering if I did this in proper way (may be I did not have correct configuration ?) or this is a bug?

 Anyone has any idea?

Thank you

How can I stop a user to push a button for 10 sec( after first click) with sessions.

$
0
0

Hi All,

How can I stop a user to push a button for 10 sec( after the first click) with sessions?

thanks


415 Unsupported Media Type on Ajax Post

$
0
0

Hi All,

I have an ASP.NET Core 2.1 web app and I am using an ajax post to the MVC controller. The data is being sent as json and the method accepts a complex class object. I have all of this working and my data is sent to the controller.

My issue is: The instant the post to the controller happens, the screen show the 415 error...so I am thinking that even though the data goes through somehow my json structure must not be correct...please advise?

View Ajax:

function SubAll() {
var selectedValues = $('#timesheet').DataTable().column(0).checkboxes.selected().toArray();

var instructions = []; //create array of objects
for (var i = 0; i < selectedValues.length; i++) {
instructions.push({ TimeId: selectedValues[i] });
}

var jsonObject = { MasterIds: instructions };

$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(jsonObject),
success: function (result) {
console.log(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};

Controller:

public IActionResult ApproveAllTimesheets([FromBody]ValueContainer information)

Class Objects:

public class ValueContainer
{
    public List<Value> MasterIds { get; set; }
}

public class Value
{
    public Guid TimeId { get; set; }
}

Payload:

{"MasterIds":[{"TimeId":"ad98749f-9083-464b-aac2-0d685a7de809"}]}

convert enum to string

$
0
0

Some one please help me out 

how to convert enum into strings. 

Angular subscribing to shared component control statusChange to disable button is not working

$
0
0

Hello,

I got an Angular dialog which uses a shared controls in another component class with validation. In my angular dialog, I used the share controls ie input textfields which two are required inputs. I can trigger the two input lines to show the Is Required validation error message. When I click on the save button, I see the form.isvalid is false.  Currently, I can't get the dialog button to disable based on the shared form valid property. I tried subscribing to the shared form  but no success so far. I would like the save button to disable when whenever the shared form valid property changes to false and enabled when all the share form control validation rules passes.

So far, here is my code.

In my shared form, which has some two input textfield lines that requires input

this.sharedForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.maxLength(60)]],
description: ['', [Validators.required, Validators.maxLength(100)]]
});
<div> <div>In my dialog code, which used the share two textfield controls and has its own buttons</div> <div></div> <div>
export class DialogComponent {
    disableSaveButton: boolean = true;
    sharedControls: SharedControlsComponent;

    ngOnInit() {
        this.sharedControls.form.statusChanges
        .subscribe(disableSaveButton => this.disableSaveButton = this.sharedControls.form.valid)
    }

}


In the HTML


<button disabled]="disableSaveButton" (click)="save()" color="primary">Save</button>
So far, the button is not doing anything. I googled and found some code where it say to use .subscibe to the statusChange of the shared component but it is not working.</div> <div></div> <div>Any help is appreciated. Thanks.</div> </div>

ModelState Contains String Required Properties Twice

$
0
0

I'm developing an Asp.Net Core 2.1 App using Razor Pages.I've come down with an odd behavior.The problem is when I submit a form,the client side validation passes with all required properties filled out,but then the validation fails with the ModelState.IsValid check,and the reason is that the ModelState contains the required string properties twice,one with the value entered and one with null value,So the validation fails!

{[BankName, Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary+ModelStateNode]}

{[BankAccount.BankName, Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary+ModelStateNode]}


See,BankAccount is the model class,and BankNameis a required property.I don't know why the property appears twice in ModelState dictionary,one with the model name(with the data entered) and one without the modelname(with null value).

Any idea why this is happening?

Asp.net core mvc and .net web api authentication combine with .net identity and jwt ?

$
0
0
I have asp.net core mvc client for front end, .net web api for data access.. i am using asp.net identity for user creation and log in . Big question how do i authenticate this user to access my web api which is a separate project. I have written code to generate jwt token but as a web api post method.... But i am not able to figure how it all fits it

1 where or how to save the token in the mvc client front end... 2 how will the token authenticate against mvc client view/controller 3 how to redirect user to log in if the token does not exists or expired? 4 how to include the token in javascript ajax calls in the mvc client? 5 .net identity core uses cookie based authentication how will this sync with jwt token ?

Any sample code would be great.....
Viewing all 9386 articles
Browse latest View live


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