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

Which publish method is the best for Win Server 2012 R2

$
0
0

Hi all,

I want to host my web site in a Win Server 2012 R2 machine

Can you tell me which publish method combination is the best;

Self-Contained Win64

or 

Framework-Dependent Portable

or

Framework-Dependent Win64


Does not redirect to local (index) after login

$
0
0

Hi,

There is a strange problem with redirection in post login action.  After entering details on login page, it doesn't redirect to homepage though it logins user. I run it in my local, after pressing login button, it stays in broweser continuing loading (and never ending), and after closing and reruning application, I see the user logged in, and I can see user's name as I injected it on my partial view. So, this means login works, but redirect action doesn't work. What's interesting, when I logout user, it redirects him successfully to home page, but on login, not.

Here is the details:

LoginViewModel

 public class LoginViewModel
    {
        public int Id { get; set; }

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

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        public bool RememberMe { get; set; }
    }
}

Account Controller

 public class AccountController : Controller
    {
        private readonly UserManager<AdUser> _userManager;
        private readonly SignInManager<AdUser> _signInManager;
        private readonly SamirDbContext _samirDbContext;
        public AccountController(UserManager<AdUser> userManager, SignInManager<AdUser> signInManager, SamirDbContext samirDbContext)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _samirDbContext = samirDbContext;
        }

        //Helper
        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

    
        [HttpGet]
        [AllowAnonymous]
        public IActionResult RegisterUser()
        {
            if (_signInManager.IsSignedIn(User))
            {
                return RedirectToAction(nameof(HomeController.Index), "Home");
            }
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> RegisterUser(RegisterViewModel registerViewModel)
        {
            if (ModelState.IsValid)
            {
                registerViewModel.SiteUser = await _samirDbContext.SiteUsers.LastOrDefaultAsync();

                AdUser adUser = await _userManager.FindByEmailAsync(registerViewModel.Email);
                if (adUser != null)
                {
                    ModelState.AddModelError("", "This user already exists");
                }
                else
                {
                    adUser = new AdUser
                    {
                        UserName = registerViewModel.UserName,
                        Email = registerViewModel.Email,
                        SiteUserId = registerViewModel.SiteUser.Id,
                        Name = registerViewModel.FullName,
                        Phone = registerViewModel.Phone
                    };

                    if(registerViewModel.Password == registerViewModel.ConfirmPassword)
                    {
                        IdentityResult userResult = await _userManager.CreateAsync(adUser, registerViewModel.Password);

                        if (userResult.Succeeded)
                        {
                            IdentityResult result = await _userManager.AddToRoleAsync(adUser, RoleType.User.ToString());

                            if (result.Succeeded)
                            {
                                await _signInManager.SignInAsync(adUser, isPersistent: false);
                                return RedirectToAction(nameof(HomeController.Index), "Home");
                            }
                            else
                            {
                                ModelState.AddModelError("", "Rol yaranmadi");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "Şifrənin tərkibində ən azı bir kiçik və böyük hərflə simvol olmalıdır");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Təsdiq şifresi fərqli yazılıb");
                    }
                }
            }
            return View(registerViewModel);
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> LoginUser(string returnUrl = null)
        {
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        } [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> LoginUser(LoginViewModel loginViewModel)
        {

            if (ModelState.IsValid)
            {
                AdUser currentuser = await _userManager.FindByEmailAsync(loginViewModel.UserName);

                Microsoft.AspNetCore.Identity.SignInResult signInResult = await _signInManager.PasswordSignInAsync(loginViewModel.UserName, loginViewModel.Password, loginViewModel.RememberMe, lockoutOnFailure: true);

                if (signInResult.Succeeded)
                {
                    var user = this.User;
                  return RedirectToAction(nameof(HomeController.Index), "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Username or password is incorrect");

                }
            }
            return View(loginViewModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> LogoutUser()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction(nameof(HomeController.Index), "Home");
        }

LoginUser View

@model Samirad.Models.ViewModels.LoginViewModel<section class="login py-5 border-top-1"><div class="container"><div class="row justify-content-center"><div class="col-lg-5 col-md-8 align-item-center"><div class="border"><h3 class="bg-gray p-4">Login Now</h3><form method="post" asp-action="LoginUser" asp-controller="Account"><div asp-validation-summary="ModelOnly"></div><fieldset class="p-4"><input asp-for="UserName" type="text" placeholder="Username" class="border p-3 w-100 my-2"><span asp-validation-for="UserName"></span><input asp-for="Password" type="password" placeholder="Password" class="border p-3 w-100 my-2"><span asp-validation-for="Password"></span><div class="loggedin-forgot"><input asp-for="RememberMe" type="checkbox" id="keep-me-logged-in"><label for="keep-me-logged-in" class="pt-3 pb-2">Keep me logged in</label></div><button type="submit" class="d-block py-3 px-5 bg-primary text-white border-0 rounded font-weight-bold mt-3">Log in</button><a class="mt-3 d-block  text-primary" href="#">Forgot Password?</a><a class="mt-3 d-inline-block text-primary" href="register.html">Register Now</a></fieldset></form></div></div></div></div></section>

Also, I'd like to add that I had similar project with the same way of coding, but that works. What might cause this problem?

The ways I tried that didn't work:

writing alternative  return Redicrects :  return RedirectToAction("Index","Home");

or adding this method and calling it on loginUser post action:

 private IActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {

                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction(nameof(HomeController.Index), "Home");
            }
        }

in LoginUser action:

return RedirectToLocal(retrunUrl)

I also cleared browser history to make sure nothing stuck on session. Again, not working.

Please, assist in solution. Thanks in advance!

Clarification Regarding The Loading of Files in bundleconfig.json

$
0
0

So I have a few files identified for loading in my bundleconfig.json as follows

[
  {"outputFileName": "wwwroot/css/site.min.css","inputFiles": ["wwwroot/css/site.css","wwwroot/css/material.min.css","wwwroot/css/bootstrap.css"
    ]
  },
  {"outputFileName": "wwwroot/js/site.min.js","inputFiles": ["wwwroot/js/site.js","wwwroot/js/globals.js","wwwroot/js/custom_db_update_user_details.js","wwwroot/js/custom.js","wwwroot/js/material.min.js","wwwroot/js/modernizr-2.6.2.js","wwwroot/js/respond.js"
    ],"minify": {"enabled": true,"renameLocals": true
    },"sourceMap": false
  }
]

The order the files that are supposed to be loaded in here don't appear to be adhered to. I have a few files in Views/Shared/_Layout.cshtml folder and load them the hard coded old way like 

<link rel="stylesheet" href="~/css/site.css" />

These appear to be loaded appropriately. What I am doing wrong, how do I get the files in the bundleconfig.json to load appropriately? 

Do I need even load any files in the _Layout.cshtml file if I'm using the bundleconfig.json?

Post table data with fixed length in ASP Core MVC

$
0
0

I have a create parent action, in the view there is a table, and every row is of type Child. The number of rows is fixed, but user might save the table without filling all the data, it requires days to fill every row. Let me show the view models first before explaining any further.

public class CreateEditParentViewModel
{
    public int Id { get; set; }
    public IList<ChildViewModel> ChildrenList { get; set; }
}

public class ChildViewModel
{
    public int Id { get; set; }
    public string Day { get; set; }
    public DateTime Date { get; set; }
    //public DateTime Time { get; set; }
    //other properties
}

as you can see, every row will have fields for date and time and since I'll be having so many rows I decided to use partial view for the row. Will be something like this:

@model TestApplication.Models.ViewModels.ChildViewModel<td><input type="hidden" asp-for="Id" /></td><td><input asp-for="Date" class="form-control" name="dob" /><span asp-validation-for="Date" class="text-danger"></span></td><td>
    time</td>

The create view:

@model TestApplication.Models.ViewModels.CreateEditParentViewModel<form method="post" asp-action="create"><table><thead><tr><th>Day</th><th>Date</th><th>Time</th></tr></thead><tbody><tr><td>1</td> @*text for now*@<partial name="_ChildPartial" /></tr><tr><td>2</td><partial name="_ChildPartial" /></tr><tr><td>3</td><partial name="_ChildPartial" /></tr></tbody></table></form>

I know this is not right because it gives the following exception.

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'TestApplication.Models.ViewModels.CreateEditParentViewModel', but this ViewDataDictionary instance requires a model item of type 'TestApplication.Models.ViewModels.ChildViewModel'.

My first concern is am I doing it the right way? Is this how I should deal with table data? The other thing, how to avoid nulls in this case? the user should fill all the cells eventually, but of course there will be so many tables with so many nulls forever. Can I not create child object (row) until its used?

is "Deploying a Netcore 3 app on ISS" really that much difficult

$
0
0

Hi,

for 2 days now I am trying to make my web site alive in Windows 10 and Windows Server 2012 and 2019. But no luck.

I am getting 500.19 and 500.31 errors constantly and can't get rid of them whatever I tried.

I follow instructions of Microsoft and other forums but nope nope nope...

What can be the problem?

Btw even though I did install it, I can't see AspNetCoreModuleV2 or AspNetCoreModule under modules. I think the problem starts from there

Can I keep netcore 2.2 runtime and 3.1 in the same server without conflict?

$
0
0

Hi all,

Can I keep netcore 2.2 runtime bundling and 3.1 in the same server without conflict?

I upgraded my project from 2.1 to 3.1 and now it is not working and I am trying to understand what is the matter

P.S: I got 500.19 error now and also 500.31 in some trials.

Help needed in documentation

$
0
0

Hi,

Core Version: 2.2

i have implemented the swagger for the documentation in my project. but i would need to implement a security for the documentation url. Basically,  there should be a username password for API and once its authenticated, the documentation page has to be called. over there, based on the username, i would need to show the API routes. since, we will give diff creds for different vendor, showing / hiding routes may vary. so, please let me know how to implement this in asp.net core 2.2 with swagger. please share me in case of any example.

Cascading SelectLists That Gets Items From Model

$
0
0

Hello everyone

I'm working on MVC project and i'm planning to create three drop down lists one for "country" and another for "province" lastly for "city"

the values for all three lists are fixed and i would like to store them in a model rather than tables in database.

when the user select a country, then the list of province will appear with the items related to the selected country the same goes for province and city.

What is the best approach for creating such cascading drop down lists?


How to get certificate .pem file

$
0
0


Hello could you help me I would like know how to get certificate .pem file contain both private and public keys ? I used dotnet core cli v2.2 and it works but how to turn code to use pem file ? 

    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    using Microsoft.IdentityModel.Tokens;
    using System;
    using System.IdentityModel.Tokens.Jwt;
    using System.Linq;
    using System.Security.Claims;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading.Tasks;

    public class Manager : Manager
    {
        private readonly ILogger<Manager> logger;
        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly byte[] SymmetricSecurityKey;

        public TokenManager(IConfiguration configuration, ILogger<Manager> logger, IHttpContextAccessor httpContextAccessor)
        {
            this.logger = logger;
            this.httpContextAccessor = httpContextAccessor;

            this.SymmetricSecurityKey = Encoding.UTF8.GetBytes(configuration["XX_Security_Bearer_SymmetricSecurityKey"]);
        }

        public async Task<string> GenerateToken(string userId, DateTime? expireTime, params Claim[] addClaims)
        {
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, userId)
            };

            if (addClaims != null)
            {
                var claimsAdd = claims.ToList();
                addClaims.ToList().ForEach(c => claimsAdd.Add(c));
                claims = claimsAdd.ToArray();
            }

            var token = new JwtSecurityToken(
              issuer: "Issuer",
              audience: "Audience",
              claims: claims,
              expires: expireTime,
              signingCredentials: BuildSigningCredentials());

            return await Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token));
        }

        public ClaimsPrincipal ValidateToken(string token)
        {
            ClaimsPrincipal claimsPrincipal = null;

            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var validationParameters = GetValidationParameters();
                claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
            }
            catch (Exception ex)
            {
                //Le token est invalide
            }

            return claimsPrincipal;
        }

        private X509Certificate2 GetCertificate2()
        {
            X509Certificate2 result = null;
            X509Store localStore = null;

            try
            {
                localStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                localStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certificates = localStore.Certificates.Find(X509FindType.FindBySubjectName, "CN(Common Name)", false);

                if (certificates.Count != 1)
                    throw new Exception("Problème dans le magasin de certificat");

                foreach (var certificate in certificates) //certificates.Cast<X509Certificate2>().FirstOrDefault();
                {
                    result = certificate;
                    break;
                }
            }
            finally
            {
                if (localStore != null)
                    localStore.Close();
            }

            return result;
        }

        private SecurityKey BuildSecurityKey()
        {
            return new RsaSecurityKey(GetCertificate2().GetRSAPublicKey()); //ou new RsaSecurityKey(cerf.GetRSAPrivateKey())
            //return new SymmetricSecurityKey(SymmetricSecurityKey);
        }

        private SigningCredentials BuildSigningCredentials()
        {
            X509SecurityKey privateKey = new X509SecurityKey(GetCertificate2());
            return new SigningCredentials(privateKey, SecurityAlgorithms.RsaSha256Signature);
            return new SigningCredentials(privateKey, "RS256");

            //return new SigningCredentials(BuildSecurityKey(), SecurityAlgorithms.HmacSha256);
        }

        private TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters()
            {
                ValidateIssuer = true,//validate the server that created that token
                ValidIssuer = "Issuer",

                ValidateAudience = true,//ensure that the recipient of the token is authorized to receive it 
                ValidAudience = "Audience",

                ValidateLifetime = true,//verify that the key used to sign the incoming token is part of a list of trusted keys

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = BuildSecurityKey(),

                ClockSkew = TimeSpan.Zero
            };
        }
    }

Passing Selected option from dropdown to controller

$
0
0

Hi, 

I'm working with Asp.net Core MVC web application project where i have a table of request to approve and reject, 

before approving request , the manger should assign (Analyst) from dropdown list. And i'm stuck on how can i pass the selected analyst to assign him for specific institution.

ViewModel

public class RequestViewModel
    {
        public IEnumerable<Request> Requests { get; set; }
        public IEnumerable<ApplicationUser> AnalystList { get; set; }
        public Institution Institution { get; set; }
        public string selectedAnalyst { get; set; }
    }

Controller

        public async Task<IActionResult> ApproveRequest(int id) 
        {
            Request Req = await _db.Request
                .Include(c => c.Institution)
                .FirstOrDefaultAsync(c => c.Id == id);

            if (Req.Type == SD.TypeRegister)
            {
                Req.Institution.Status = SD.StatusApproved;
                Req.Institution.ApprovalDate = DateTime.Now;
                Req.Institution.Seats = Req.Seats; // new

                //Here i want to get the analyst ID.

            }
            else if (Req.Type == SD.TypeSeat)
            {
                Req.Institution.Seats += Req.Seats;
            }
            else if (Req.Type == SD.TypeSubscription)
            {
                Req.Institution.Seats = Req.Seats;
                Req.Institution.Status = SD.StatusApproved;
                Req.Institution.ApprovalDate = DateTime.Now;
            }

            Req.isDone = true;
            await _db.SaveChangesAsync();
            return await CreateApproval(id, SD.StatusApproved);
        }

View

@model TestApplication.Models.ViewModels.RequestViewModel<---Lines of Code--->

      @foreach (var item in Model.Requests)
                        {
                            @if (item.Type == "Register" && item.Institution.Status == "Pending") @*need one*@
                            {<tr><td>
                                        @Html.DisplayFor(m => item.Institution.Name)</td><td>
                                        @Html.DisplayFor(m => item.Date)</td><td>
                                        @Html.DisplayFor(m => item.Institution.Seats)</td><td>
                                        @Html.DisplayFor(m => item.ActualSeats)</td><td>
                                        @Html.DisplayFor(m => item.Seats)</td><td><select asp-for="selectedAnalyst" asp-items="Model.AnalystList.ToSelectListItem(Model.selectedAnalyst)" class="form-control"><option selected value="">--- Choose ---</option>
//From this dropdown list, i want to pass the selected analyst to my controller action.</select></td><td><a class="btn btn-info" asp-controller="Request" asp-action="ApproveRequest" asp-route-id="@item.Id"> accept </a><a class="btn btn-info" asp-controller="Request" asp-action="RejectRequest" asp-route-id="@item.Id"> Reject </a></td><td><button type="submit" class="btn btn-success anchorDetail" data-target="#modal-@item.Institution.Id" data-toggle="modal"> Details</button></td><td><div class="modal fade" id="modal-@item.Institution.Id" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog-centered modal-dialog" role="document"><div class="modal-content"><div class="modal-header bg-success text-light justify-content-center"><h5 class="modal-title">Details</h5></div><div class="modal-body justify-content-center" id="MyModalContent"> @await Html.PartialAsync("_RequestDetails", item)</div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button></div></div></div></div></td></tr> } }

could we write word press plugin with asp.net

$
0
0

I want to write an word press plugin whit asp.net in order to add sum special services that are not support by ordinary plugin . 

<div id="skyroom-extension-is-installed"></div>

Encrypt sections of the appsettings.json inside my Asp.Net Core MVC web apllication

$
0
0

I have the following `appsettings.json` inside my asp.net core MVC web application:-

   {"ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\ProjectsV13;Database=LandingPage;Trusted_Connection=True;"
      },"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
        }
      },"AllowedHosts": "*","SMTP": {"pass": "************"
      }
    }

where i am storing an smtp password + when i publish the application to a shared host provider, i will add an sql server username and password inside the appsettings.json's connection string.

so my question is how i can encrypt sections inside my `appsettings.json` hosted inside a remote shared hosting provider inside IIS? i am fine with keeping the password inside visual studio project, but i want to encrypt the hosted appsettings.json? is this possible?

Thanks

How Would I Go About Correctly Caching My Images In This Scenario

$
0
0

I currently have my default Index() action in my HomeController that returns images in a json format with the actual physical url of the image on the server, the problem with this is that it hits the server everytime that the Index() action is called. What alternative method can I use to cache the images?

how can I call Razor file from cshtml

$
0
0

I am trying to create Delete Confirmation dialogue as a general component file to call   from    everywhere in the project for deleting  purpose of the record. I created   Delete Confirmation  razor file as component  and I want to call the razor file from other delete screen

Here is my component

// ConfirmBase.cs
namespace LibraryBooks.ViewComponents
{
    public class ConfirmBase : ComponentBase
    {
        protected bool ShowConfirmation { get; set; }
        [Parameter]
        public string ConfirmationTitle { get; set; } = "Delete confirmation";
        [Parameter]
        public string ConfirmationMesssge { get; set; } = "Are you sure you want to Delete ?";

        public EventCallback<bool> ConfirmationChanged { get; set; }
        protected async Task OnConfirmationChange(bool value)
        {
            ShowConfirmation = false;
            await ConfirmationChanged.InvokeAsync(value);
        }
    }
}
Confirm.Razor
@inherits ConfirmBase<div class="modal fade show d-block " id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="exampleModalLabel">@ConfirmationTitle</h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"
                            @onclick="() => OnConfirmationChange(false)"><span aria-hidden="true">&times;</span></button></div><div class="modal-body">
                    @ConfirmationMesssge</div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal"
                           @onclick="() => OnConfirmationChange(false)">Cancel</button><button type="button" class="btn btn-danger"
                             @onclick="() => OnConfirmationChange(true)">Delete</button></div></div></div></div>

How can I call  the Confirm.razor from my Index.cshtml

<button type="button" class="btn btn-danger m-1" onclick="Delete_Click">                                 
                                Delete</button>

Index controller

public IActionResult Delete_Click()
        {
             return View(); // Here I would like to call Confirm.razor
        }

Please  help how can I call the razor file

cannot get parameters from ajax call to controller razor

$
0
0

Simple usecase - get PartialView dynamically from AJAX call to update div in my main page after input select (dropdownlist) changed value.

Steps I took:

  1. Created view (only, wihtout PageModel) with model declared with @model ViewModelCreateOperation.
  2. Created checkbox on main page:
<selectclass="form-control"asp-items="@(new SelectList(Model.allExistingOperations))"onchange="PopulateForm(this.value);returnfalse;"></select>
  1. created scripts on main page:
<script>functionPopulateForm(value){var dataToPost ="{ operationName:"+ value +"}";;$.ajax({
                type:"post",
                url:'@Url.Content("/MeaningOfLifeRoutedName")',
                data: dataToPost ,
                contentType :'application/json; charset=UTF-8',
                success:function(data){$('#lubieplacki').html(data);},
                error:function(xhr, ajaxOptions, thrownError){if(xhr.status ==404){
                        alert(thrownError);}}});}</script>
  1. created Controller in Controllers folder to return PartialView (becouse I cannot use "return PartialView("someview", someModel)" with PageModel already used as a inherit class.
namespaceMyMysteriousApplication.Controllers{[Route("MeaningOfLifeRoutedName")]publicclassMeaningOfLifeChangesController:Controller{privatereadonlyMyMysteriousApplication.Models.TTSCDBContext _context;publicMeaningOfLifeChangesController(MyMysteriousApplication.Models.TTSCDBContext context){
            _context = context;}publicViewModelCreateOperation viewModelCreateOperation {get;set;}publicIActionResultIndex(){returnRedirectToPage("../Index");}[HttpPost]publicActionResult getMeaningOfLife(string operationName){
            viewModelCreateOperation =newViewModelCreateOperation();


            viewModelCreateOperation =newViewModelCreateOperation();
            viewModelCreateOperation._entitiesSelectListItem = _context.Entities.Select(a =>newMicrosoft.AspNetCore.Mvc.Rendering.SelectListItem(){Value= a.Id.ToString(),Text= a.EntityName}).OrderByDescending(u => u.Text).ToList();



            viewModelCreateOperation.MeaningOfLifeChanges= _context.MeaningOfLifeChanges.Where(u => u.OperationName.Contains(operationName)).OrderBy(u => u.ChangeId).FirstOrDefault();returnPartialView("../projectManagement/partialViewCreateNewMOL", viewModelCreateOperation);}}}

Primary question: I got null in parameters - I don't get why:enter image description here

Bonus question: I couldn't invoke my controller in any way (tried "/MeaningOfLifeChangeController/getMeaningOfLife" or "/MeaningOfLifeChange/getMeaningOfLife", with "~/MeaningOfLifeChangeController/getMeaningOfLife" and others combinations), so I added [Route("MeaningOfLifeRoutedName")] and [HttpPost] before method. I don't get why... in Startup I have added controllers to initialize (JSON is for other stuff(API)):

services.AddControllersWithViews().AddJsonOptions(options =>{
             options.JsonSerializerOptions.PropertyNameCaseInsensitive=true;
             options.JsonSerializerOptions.PropertyNamingPolicy=null;
             options.JsonSerializerOptions.MaxDepth=150;}).AddRazorRuntimeCompilation();


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

App Service integrated with Azure key vault - configuration inside an array

$
0
0

I have an API that is installed inside an App Service in Azure, made in .Net Core 3.1. It is integrated properly with Azure key vault, where we store our secrets. But there are some sensitive settings inside our appsettings.json that I'd like to store as secrets inside Key vault, and this is quite easy to achieve by setting the key with the path of the configuration, such as:

settings-someSetting-key

But the thing is that my settings are inside an array, something like this:

{"tenantSettings":[{"tenantId": 1,"repositories": [{"name": "repo1","connectionString": "cs"
            },
            {"name": "repo2","connectionString": "cs"
            }
        ]
    },
    {"tenantId": 2,"repositories": [{"name": "repo3","connectionString": "cs"
            },
            {"name": "repo4","connectionString": "cs"
            }
        ]
    }
]

}

So when I store the path of the configuration in order to match the secret with the setting, this is not working well, and I'm also not sure how I would do it.

Let's say I want to resolve repo1 connection string, what whould be the path?

tenantSettings--repositories[0]--connectionString?

I'm unable to make this work, has anyone ever face the same situation?

How To Install Jquery UI in .net core 3.1

$
0
0

I have gone to the package manager and selected jquery ui combined and installed the package, I now want to load this library into my project but can't find the relevant jQuery UI files anywhere under the wwwroot folder. How do I install this and reference it properly in my project?

Cant Post Form Data to Custom Handler...

$
0
0

Hello Folks,

I have the following form and java script in my ASP.NET Core Razor Page.

Here is the form :

<form id="updatetaskdetails" method="post"><div class="modal-body"><input type="hidden" class="form-control" id="TaskID" value="@Model.taskDetails.TaskID"><input type="hidden" class="form-control" id="TaskDetailsId"><div class="form-group"><label for="IncidentDate" class="col-form-label">تاريخ النشاط</label><input type="date" class="form-control" id="IncidentDate"></div><div class="form-group"><label for="TaskDetailsName" class="col-form-label">اسم نشاط</label><input type="text" class="form-control" id="TaskDetailsName"></div><div class="form-group"><label for="TaskDetailsDesc" class="col-form-label">نشاط</label><textarea class="form-control" id="TaskDetailsDesc"></textarea></div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">أغلق</button><button id="UpdateDetails" type="button" class="btn btn-primary">تحديث التفاصيل</button></div></form>

Here is the code from where I fill  values the form using Jquery 

<script>$('#updatedetail').click(function () {$('input:checkbox[name=TaskDetailsID]').each(function () {
                if ($(this).is(':checked')) {

                    var TaskDetailsID = $(this).val();
                    var dataToPost = TaskDetailsID;$.getJSON("/TaskDetails?handler=DetailByID", { dataToPost: dataToPost }, function (TaskDetails) {

                        var taskdetail = jQuery.parseJSON(TaskDetails);

                        $(".modal-body #TaskID").attr('value',taskdetail.TaskID);$(".modal-body #TaskDetailsId").attr('value', taskdetail.TaskDetailsId);$(".modal-body #IncidentDate").attr('value', taskdetail.IncidentDate.substr(0, 10));$(".modal-body #TaskDetailsName").attr('value', taskdetail.TaskDetailsName);$(".modal-body #TaskDetailsDesc").val(taskdetail.TaskDetailsDesc);$("#update").modal('show');
                    });
                }
            });
        });</script>


Here is the Event when somebody press the update details button.

<script>$(function () {$("#UpdateDetails").click(function (e) {$.ajax(
                            {
                                type: "POST",
                                url: "@Url.Page("/TaskDetails")?handler=UpdateDetail",
                                data: $('#updatedetail').serialize(),
                                headers: {
                                    RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
                                },
                                success: function (data) {
                                    if (data) {
                                        window.location.href = '@Url.Page("TaskDetails", new { id= @Model.taskDetails.TaskID }  )';
                                    }
                                    else {
                                        window.location.href = '@Url.Page("TaskDetails", new { id= @Model.taskDetails.TaskID }  )';
                                    }
                                },
                                error: function (xhr, textStatus, errorThrown) {
                                    alert(errorThrown);
                                }
                                });
                 });
            });</script>

Now the problem is the Jquery AJAX does fire the custom handler UpdateDetail. But I am unable to receive the submitted form values. Can Anyone tell me what I am doing wrong?

Here it  code behind file.

  public JsonResult OnPostUpdateDetail()
        {
            try
            {
                TaskBO task = new TaskBO();

                var t = Convert.ToInt32(Request.Form["TaskDetailsId"]);

                TaskDetailsViewModel details = new TaskDetailsViewModel()
                {
                    TimeLineDetails = new TimeLineDetails
                    {
                        TaskDetailsID = Convert.ToInt32(Request.Form["TaskDetailsId"]),
                        IncidentDate = Convert.ToDateTime(Request.Form["IncidentDate"]),
                        TaskDetailsName = Request.Form["TaskDetailsName"],
                        TaskDetailsDesc = Request.Form["TaskDetailsDesc"]
                    }
                };
                //task.AddTaskDetails(details);
                return new JsonResult(new { data = true });
            }
            catch (Exception)
            {

                throw;
            }
        }

Which publish method is the best for Win Server 2012 R2

$
0
0

Hi all,

I want to host my web site in a Win Server 2012 R2 machine

Can you tell me which publish method combination is the best;

Self-Contained Win64

or 

Framework-Dependent Portable

or

Framework-Dependent Win64

Viewing all 9386 articles
Browse latest View live


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