PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label razor-pages. Show all posts
Showing posts with label razor-pages. Show all posts

Tuesday, December 13, 2022

[FIXED] How to Join and Display Data from two models on a single razor page (no mvc)

 December 13, 2022     foreign-keys, inner-join, razor-pages, syntax     No comments   

Issue

I have two models (Child and Shot) that I would like to join so that I can display information on a single razor page.

This small historical view app basically has client demographics in one model (Model Name is Child) and client immunizations in another table (Model Name is Shot). I have an index page that a user will click a 'View Immunization Details' details button next to a client's ID number and client name. This will take them to the page where I would like the joined data to display.

The top half of the page will display the demographics (ID, name, address, date of birth, etc) from the Child model and the lower half of the page will display a table of any immunization info for that particular client (from the Shot model). (immunization date, dose, shot description, etc)

This is a one to many relationship between Child and Shot. One Child record can have many Shot records.

In reviewing how to get two models to display on one page I have only seen where the data did NOT need to be filtered by the results from one model. As stated above, I need to show ONLY the shots that pertain to a SINGLE client on the Details page, NOT all shots from the Shot table.

Here is my code as I have it so far:

First, the Child model:

using System.ComponentModel.DataAnnotations;

namespace HealthyShots.Models
{
    public class Child
    {
        [Key]
        [Display(Name ="Child ID")]
        public int ChildId { get; set; }
        public List<Shot> Shots { get; set; }
        [Display(Name ="Last Name")]
        public string? LastName { get; set; }
        [Display(Name = "First Name")]
        public string? FirstName { get; set; }
        [Display(Name = "MI")]
        public string? MiddleInitial { get; set; }
        [Display(Name = "Full Name")]
        public string FullName
        {
            get
            {
                return LastName + ", " + FirstName + " " + MiddleInitial;
            }
        }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        [Display(Name = "Date of Birth")]
        public DateTime? BirthDate { get; set; }
        public string? Addr1 { get; set; }
        public string? Addr2 { get; set; }
        public string? City { get; set; }
        public string? State { get; set; }
        public string? Zip { get; set; }
    }
}

Then, the Shot model:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace HealthyShots.Models
{
    public class Shot
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int ShotId { get; set; }

        [Required]
        public int ChildId { get; set; }
        public Child Child { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        [Display(Name = "Immunization Date")]
        public DateTime? Date { get; set; }
        public string? Dose { get; set; }
        [Display(Name = "Shot Number")]
        public int? ShotNo { get; set; }
        [Display(Name ="Shot Description")]
        public string? ShotDesc { get; set; }
    }
}

Then, my .cs (so far) for the Details razor page:

using HealthyShots.Data;
using HealthyShots.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace HealthyShots.Pages.Details
{
    public class DetailsModel : PageModel
    {
        private readonly ApplicationDbContext _db;

        public Child Child { get; set; }
        public Shot Shot { get; set; }
        

        public DetailsModel(ApplicationDbContext db)
        {
            _db = db;
        }
        
        public void OnGet(int Id)
        {
            _db.Child
                .Include(child => child.Shots)
                .FirstOrDefault(child => child.ChildId == Id);
        }

    }
}

And my razor view:

@page
@model HealthyShots.Pages.Details.DetailsModel

@{
    ViewData["Title"] = "Immunization Details";
}

<h2>Details</h2>

<div>
    <h4>Demographic Information</h4>
    <hr />

        <table class="table table-bordeless" style="width:100%">
            <tr>
                <td style="width: 10%">
                    <div class="mb-3">
                        <label asp-for="Child.ChildId"></label>
                        <input asp-for="Child.ChildId" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 30%">
                    <div class="mb-3">
                        <label asp-for="Child.LastName"></label>
                        <input asp-for="Child.LastName" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 30%">
                    <div class="mb-3">
                        <label asp-for="Child.FirstName"></label>
                        <input asp-for="Child.FirstName" class="form-control"/>
                    </div>
                </td>
                <td style="width: 5%">
                    <div class="mb-3">
                        <label asp-for="Child.MiddleInitial"></label>
                        <input asp-for="Child.MiddleInitial" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 25%">
                    <div class="mb-3">
                        <label asp-for="Child.BirthDate"></label>
                        <input asp-for="Child.BirthDate" type="date" disabled class="form-control"/>
                    </div>
                </td>
            </tr>
        </table>
        <table class="table table-bordeless" style="width:100%">
            <tr>
                <td style="width: 25%">
                    <div class="mb-3">
                        <label asp-for="Child.Addr1"></label>
                        <input asp-for="Child.Addr1" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 25%">
                    <div class="mb-3">
                        <label asp-for="Child.Addr2"></label>
                        <input asp-for="Child.Addr2" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 25%">
                    <div class="mb-3">
                        <label asp-for="Child.City"></label>
                        <input asp-for="Child.City" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 5%">
                    <div class="mb-3">
                        <label asp-for="Child.State"></label>
                        <input asp-for="Child.State" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 20%">
                    <div class="mb-3">
                        <label asp-for="Child.Zip"></label>
                        <input asp-for="Child.Zip" disabled class="form-control"/>
                    </div>
                </td>
            </tr>
        </table>
<br />
<br />


    <h4>Immunizations</h4>
    <hr />

          <table class="table table-bordeless" style="width:100%">
            <tr>
                <td style="width: 20%">
                    <div class="mb-3">
                        <label asp-for="Shot.Date"></label>
                        <input asp-for="Shot.Date" type="date" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 20%">
                    <div class="mb-3">
                        <label asp-for="Shot.Dose"></label>
                        <input asp-for="Shot.Dose" disabled class="form-control"/>
                    </div>
                </td>
                <td style="width: 60%">
                    <div class="mb-3">
                        <label asp-for="Shot.ShotDesc"></label>
                        <input asp-for="Shot.ShotDesc" disabled class="form-control"/>
                    </div>
                </td>
            </tr>
            }
        </table>

    <a asp-page="/Children/Index">Back to List</a>
</div>

I know I am missing code. I have googled and searched here for how the foreign key works, but still don't fully understand it. I realize that I have to tell Visual Studio that the Id (in the Child model) must be the same as the ChildId (in the Shot model), but I am not sure WHERE to do that or WHAT the correct syntax is.

I also need a wee bit of guidance on how to reference these items on the razor page. Once they are joined via foreign key, can I just access them with asp tag helpers like I would if it were a single model being referenced? Like I have done in my code so far?

Thanks in advance for any guidance you can provide. I am a beginner, so please understand that when you frame your answer.


Solution

Create relationships using conventions

In EF Core one way to define entity relationships is using conventions. This means you have to add specific properties with specific names to your entities so that EF understands the relationship between them.

Example:

public class Child
{
    public int ChildId { get; set; }

    public List<Shot> Shots { get; set; }
}

public class Shot
{
    public int ShotId { get; set; }

    public int ChildId { get; set; }
    public Child Child { get; set; }
}

In the above scenario EF will automatically create a 1 to many relationship between Shot and Child. One shot is linked to one child but one child can be linked to multiple shots. Shot.ChildId will be a foreign key to Child.ChildId.

https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship

Loading related data from database

Now if you want to retrieve a specific child from database with all the related shots you can do:

var child = _db.Child
    .Include(child => child.Shots)
    .FirstOrDefault(child => child.ChildId == Id);

Include method tells EF to populate Child.Shots with all the shots that are related to this kid.

Similarly if you when you load the shots you can do:

var shots = _db.Shot
    .Include(shot => shot.Child)
    .ToList();

https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager

Configure relationships manually

You can also configure relationships manually:

https://www.learnentityframeworkcore.com/configuration/one-to-many-relationship-configuration



Answered By - Dimitris Maragkos
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 19, 2022

[FIXED] How to change bootstrap 4 grid system to fit mobile elegantly

 November 19, 2022     bootstrap-4, javascript, jquery, media-queries, razor-pages     No comments   

Issue

I have 3 steps form and in each row in it contains many inputs like thisclick here to see my form
and here a sample of the gird system i used

 <div class="row">
<div class="col">
<input asp-for="First_Name_AR" class="form-control" />
</div>
<div class="col">
<input asp-for="Second_Name_AR" class="form-control" />
</div>
<div class="col">
<input asp-for="Father_Name_AR" class="form-control" />
</div>
</div>

the problem when using mobile it will be like this : click here
So what I want is to make this form fit mobile beautifully like to set one input in each row like this

  <div class="row">
<div class="col">
<input asp-for="First_Name_AR" class="form-control" />
</div>
    </div>
<div class="row">
<div class="col">
<input asp-for="Second_Name_AR" class="form-control" />
</div>
    </div>
<div class="row">
<div class="col">
<input asp-for="Father_Name_AR" class="form-control" />
</div>
    </div>

is there any idea using @media query or javascript solutions?


Solution

You are using Bootstrap grid wrong. You put each col in a separate row. Instead, put all columns inside the same row. Then change the class from col to col-md-4.

The class col-md-4 means the following:

  • If the viewport width >= 768px: there will be three columns beside each other.
  • If the viewport width < 768px: columns will be stacked above each other.

See the snippet below.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>

<div class="row">
  <div class="col-md-4">
    <input asp-for="First_Name_AR" class="form-control" />
  </div>
  <div class="col-md-4">
    <input asp-for="Second_Name_AR" class="form-control" />
  </div>
  <div class="col-md-4">
    <input asp-for="Father_Name_AR" class="form-control" />
  </div>
</div>



Answered By - Cervus camelopardalis
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, September 30, 2022

[FIXED] How can I apply Bootstrap 5 validation to a Razor form?

 September 30, 2022     bootstrap-5, razor-pages, validation     No comments   

Issue

I have Razor Pages form like this:

    <form id="account" method="post">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-floating mb-3">
            <input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" />
            <label asp-for="Input.Email" class="form-label"></label>
            <span asp-validation-for="Input.Email" class="text-danger"></span>
        </div>
...

in the output i get the following render:

    <form id="account" method="post">
        <div class="form-floating mb-3">
            <input class="form-control" autocomplete="username" aria-required="true" type="email" data-val="true"
                data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required."
                id="Input_Email" name="Input.Email" value="">
            <label class="form-label" for="Input_Email">Email</label>
            <span class="text-danger field-validation-valid" data-valmsg-for="Input.Email" data-valmsg-replace="true"></span>
        </div>
...

But Bootstrap v5 uses the :invalid and :valid styles applied to form controls. At the same time, data-val- attributes are not taken into account in any way.

Is it possible to seamlessly connect the Bootstrap 5 validation functionality on the client while retaining all the power of customizing the Razor Pages validation model?


Solution

After reading the documentation for the ValidityState object and the JS Forms API. And by combining this with Bootstrap Validation, we got the following solution for the following validation properties: valueMissing, typeMismatch (email), tooLong, tooShort. The list is not complete, the solution can be developed to suit your needs.

<script type="text/javascript">
    (() => {
        'use strict'

        function validateControl(c) {
            c.addEventListener('input', (event) => setErrMessage(c));
        }

        function setErrMessage(c) {

            const name = c.getAttribute('name');
            const errMsg = Array.from(c.parentElement
                .querySelectorAll(`[data-valmsg-for="${name}"]`))
                .filter(msg => !!msg.getAttribute('data-valmsg-replace'));

            errMsg.forEach(msg => msg.innerText = '');

            c.required = !!c.getAttribute('aria-required');

            const requiredErrorMessage = c.getAttribute('data-val-required');
            if (requiredErrorMessage && c.validity.valueMissing)
                errMsg.forEach(msg => msg.innerText = requiredErrorMessage);

            const typeMismatchErrorMessage = c.getAttribute('data-val-email');
            if (typeMismatchErrorMessage && c.validity.typeMismatch)
                errMsg.forEach(msg => msg.innerText = typeMismatchErrorMessage);

            const lengthMax = c.getAttribute('data-val-length-max');
            const lengthMin = c.getAttribute('data-val-length-min');
            if (lengthMin)
                c.setAttribute('minlength', +lengthMin)

            const lengthErrorMessage = c.getAttribute('data-val-length');
            if (lengthErrorMessage && (c.validity.tooLong || c.validity.tooShort))
                errMsg.forEach(msg => msg.innerText = lengthErrorMessage);

        }

        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        const forms = document.querySelectorAll('form')
        // Loop over them and prevent submission
        Array.from(forms).forEach(form => {

            form.noValidate = true;

            const controls = form.querySelectorAll('[data-val="true"]');

            Array.from(controls).forEach(validateControl);

            form.addEventListener('submit', event => {

                Array.from(controls).forEach(setErrMessage);

                const isValid = form.checkValidity();

                if (!isValid) {
                    event.preventDefault()
                    event.stopPropagation()
                }

                form.classList.add('was-validated')

            }, false)
        })
    })()
</script>


Answered By - Igor N.
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, September 8, 2022

[FIXED] How to call a post handler from a ajax render function and pass the value

 September 08, 2022     ajax, asp.net-core, datatable, post, razor-pages     No comments   

Issue

Here's my code. The post handler in the render function does not get called. It keeps going to the GET handler when clicked. The a href tag works fine but i dont want to pass the id value in the url. So, I want to call a post and then do a redirect.

@section Scripts {
        <script>
 
            $(document).ready(function () {
               
                    $.ajax({
                        serverSide: true,
                        type: "Get",
                        url: "/SRes?handler=Json",
                        dataType: "json",
                        success: OnSuccess,
                        beforeSend: function () {
                            console.log('before send')
                            $('#loadModal').show();
                        },
                        complete: function () {
                            console.log('complete send')
                            $('#loadModal').hide();
 
                        }
 
                    });
 
 
            });
 
 
            function OnSuccess(response) {
                console.log(response.data)
 
                $('#myTable').DataTable(
                    {
                        "dom": '<"top"Blf>rt<"bottom"rip><"clear">',
                        buttons: [
 
                            'excel', 'pdf', 'print'
                        ],
 
                        scrollY: "400",
                        pageLength: 25,
                        data: response.data,
                        columns: [{
                            className: 'details-control',
                            orderable: false,
                            data: null,
                            defaultContent: ''
 
                        },
 
                        {
                            "data": "Id",
                            "render": function (data, type, row, meta) {
                                if (type === 'display') {
                                    /* data = '<a target="_blank" href="/details?id=' + data + '">' + data + '</a>';*/
                                    /*  data = '<asp:LinkButton ID="LinkButton1" runat="server" OnClick="Details">Test</asp:LinkButton>';*/
                                    data = '<form asp-page-handler=”Details” method=”post”><button type=”submit” class=”btn btn-default”>Save Data</button></form>';
                                }
 
                                return data;
                            }
 
                        },
                        { "data": "name" },
                        { "data": "desc" },
                        { "data": "address" },
                        { "data": "Type" },
                            /* { "data": "status" }*/
                        ],
 
                        initComplete: function (settings, json) {
 
                            $('#myTable').DataTable().columns.adjust();
                            $('#myTable').DataTable().fixedHeader.adjust();
                        },
 
                    });
 
 
                $('#myTable tbody').on('click', 'td.details-control', function () {
                    var table = $('#myTable').DataTable();
                    var tr = $(this).closest('tr');
                    var row = table.row(tr);
 
                    if (row.child.isShown()) {
                        row.child.hide();
                        tr.removeClass('shown');
                    }
                    else {
                        row.child(format(row.data())).show();
                        tr.addClass('shown');
                    }
                });
 
 
            };
 
            function format(rowData) {
                //var div = $('<div/>')
 
                //div.append(rowData.DOB);
                //div.append(rowData.filingDate);
                //div.append(rowData.type);
                // `d` is the original data object for the row
                return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
                    '<tr>' +
                    '<td>Case Filing Date:</td>' +
                    '<td>' + rowData.recDate + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>Case Type:</td>' +
                    '<td>' + rowData.type + '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>Date of Birth:</td>' +
                    '<td>'+ rowData.DOB + '</td>' +
                    '</tr>' +
                    '</table>';
 
 
                return div;
            }
 
 
        </script>
    }
 
 

Here's my code behind. I would like to pass the value of the id to this function. I am using razor pages.

  public IActionResult OnPostDetails()
            {
                return RedirectToPage("./cust");
            }

Solution

You need to use html code rather than tag helper in DataTable.It will not be generated to html code automatically.When using action in post form,the AntiForgeryToken will not be included in the form.So you need to add it to the forms in initComplete.Try to use the following code: html:

<div id="AntiForgeryToken">
    @Html.AntiForgeryToken()
</div>
...

js:

$('#myTable').DataTable(
                    {
                        "dom": '<"top"Blf>rt<"bottom"rip><"clear">',
                        buttons: [
 
                            'excel', 'pdf', 'print'
                        ],
 
                        scrollY: "400",
                        pageLength: 25,
                        data: response.data,
                        columns: [{
                            className: 'details-control',
                            orderable: false,
                            data: null,
                            defaultContent: ''
 
                        },
 
                        {
                            "data": "Id",
                            "render": function (data, type, row, meta) {
                                if (type === 'display') {
                                  
                                    data = '<form name="testForm" action="?handler=Details" method="post"><input name="id" hidden value="'+data+'" /><button type="submit" class="btn btn-default">Save Data</button></form>';
                                }
 
                                return data;
                            }
 
                        },
                        { "data": "name" },
                        { "data": "desc" },
                        { "data": "address" },
                        { "data": "Type" },
                            /* { "data": "status" }*/
                        ],
 
                        initComplete: function (settings, json) {
                             $("form[name='testForm']").each(function (index) {
                            $("form[name='testForm']")[index].innerHTML = $("form[name='testForm']")[index].innerHTML + document.getElementById("AntiForgeryToken").innerHTML;
                        })
                            $('#myTable').DataTable().columns.adjust();
                            $('#myTable').DataTable().fixedHeader.adjust();
                        },
 
                    });

OnPostDetails:

public IActionResult OnPostDetails(int id)
            {
                return RedirectToPage("./cust");
            }


Answered By - Yiyi You
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 4, 2022

[FIXED] How can I redirect an already logged user to Index in Asp .Net Core web Application (razor pages)

 September 04, 2022     asp.net-core, authentication, c#, razor-pages, web-applications     No comments   

Issue

I want to avoid users getting into the login page if already authenticated.

I know that you can use the RedirectToPage("/index") but i don`t know were.

I've tried this:

@page
@model xxxxx.Accounts.LoginModel
@{
    Layout = "EmptyLayout";
    if (User.Identity.IsAuthenticated)
          RedirectToPage("/index")
}

<!doctype html>
<html lang="es">
//login page

This don't work for me and I know that if (User.Identity.IsAuthenticated) is true, and in the PageModel the Redirect("") method works properly.

Is there any PageModel method like OnCreate(), OnLoad(),... to run code before the page is loaded? How can I achive this?


Solution

I belive that i was not on debug mode so i didn't get the breakpoint on the OnGet(). So the solution is just to do this:

public async Task<IActionResult> OnGet()
        {
            if (User.Identity.IsAuthenticated)
                return Redirect("/Index");
            else return Page();

        }


Answered By - F3rkun
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I redirect an already logged user to Index in Asp .Net Core web Application (razor pages)

 September 04, 2022     asp.net-core, authentication, c#, razor-pages, web-applications     No comments   

Issue

I want to avoid users getting into the login page if already authenticated.

I know that you can use the RedirectToPage("/index") but i don`t know were.

I've tried this:

@page
@model xxxxx.Accounts.LoginModel
@{
    Layout = "EmptyLayout";
    if (User.Identity.IsAuthenticated)
          RedirectToPage("/index")
}

<!doctype html>
<html lang="es">
//login page

This don't work for me and I know that if (User.Identity.IsAuthenticated) is true, and in the PageModel the Redirect("") method works properly.

Is there any PageModel method like OnCreate(), OnLoad(),... to run code before the page is loaded? How can I achive this?


Solution

I belive that i was not on debug mode so i didn't get the breakpoint on the OnGet(). So the solution is just to do this:

public async Task<IActionResult> OnGet()
        {
            if (User.Identity.IsAuthenticated)
                return Redirect("/Index");
            else return Page();

        }


Answered By - F3rkun
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 31, 2022

[FIXED] How to edit files in a database with razor?

 July 31, 2022     asp.net-core, database, file-upload, razor-pages     No comments   

Issue

I want to create razor pages that perform CRUD operations on files in a sql database. I managed to upload files to the database using IFormFile and MemoryStream but I am not able to update/replace them in the same way. When I select the new file and click on Save, I get a message that no file was selected.

I tried the following code

File.cs

namespace MyApp.Models
{
    public class File
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public byte[]? Content { get; set; }
    }
}
Edit.cshtml

@page
@model MyApp.Pages.Files.EditModel

@{
    ViewData["Title"] = "Edit";
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

<h1>Edit</h1>

<h4>File</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="File.Id" />
            <div class="form-group">
                <label asp-for="File.Title" class="control-label"></label>
                <input asp-for="File.Title" class="form-control" />
                <span asp-validation-for="File.Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="File.Description" class="control-label"></label>
                <input asp-for="File.Description" class="form-control" />
                <span asp-validation-for="File.Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FileUpload.FormFile"></label>
                <input asp-for="FileUpload.FormFile" type="file">
                <span asp-validation-for="FileUpload.FormFile"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="./Index">Back to List</a>
</div>

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

#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using MyApp.Data;
using MyApp.Models;

namespace MyApp.Pages.Files
{
    public class EditModel : PageModel
    {
        private readonly ApplicationDbContext _context;

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

        [BindProperty]
        public File File { get; set; }

        [BindProperty]
        public BufferedSingleFileUploadDb FileUpload { get; set; }

        public class BufferedSingleFileUploadDb
        {
            [Required]
            [Display(Name = "File")]
            public IFormFile FormFile { get; set; }
        }

        public async Task<IActionResult> OnGetAsync(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            File = await _context.File.FirstOrDefaultAsync(m => m.Id == id);

            if (File == null)
            {
                return NotFound();
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            using (var memoryStream = new MemoryStream())
            {
                await FileUpload.FormFile.CopyToAsync(memoryStream);

                // Upload the file if less than 2 MB
                if (memoryStream.Length < 2097152)
                {
                    File.Content = memoryStream.ToArray();
                }
                else
                {
                    ModelState.AddModelError("File", "The file is too large.");
                }
            }

            _context.Attach(File).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FileExists(File.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return RedirectToPage("./Index");
        }

        private bool FileExists(string id)
        {
            return _context.File.Any(e => e.Id == id);
        }
    }
}

Solution

Add enctype="multipart/form-data" to your form element. – Mike Brind



Answered By - Hao Wang
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 13, 2022

[FIXED] Where can I find or add the _AppStart & _PageStart in ASP.NET projects?

 July 13, 2022     asp.net, asp.net-mvc, c#, razor-pages, web-deployment     No comments   

Issue

Let me start off by saying I've seen a StackOverflow question related to this but there's no question like this I want to ask!

In my learning journey of the framework ASP.NET, I find a little problem. When I create any new ASP.NET project using the dotnetCLI. by standard the projects are missing two files that i'm looking for the _AppStart and _PageStart. Where can i find them or how can i add them? Thanks


Solution

The _AppStart and _PageStart files belong to the old ASP.NET Web Pages framework. They are not supported in the new Razor Pages framework, which is what you are using when you create applications using the CLI.

The equivalent to _AppStart in Razor Pages is the Program.cs file (.NET 6 onwards) or the Configure method in Startup (ASP.NET Core 2 - 5). The replacement for the _PageStart file is _ViewStart.

The Web Pages framework is more or less dead. Two of its four pillars have been deprecated (SQL CE and WebMatrix) and the recommendation these days is that you use Razor Pages instead.

https://www.learnrazorpages.com

https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-6.0&tabs=visual-studio



Answered By - Mike Brind
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, April 28, 2022

[FIXED] Why do I get this warning: '@Model.property' is not a valid value of attribute 'checked'?

 April 28, 2022     asp.net-core, checkbox, compiler-warnings, razor-pages, warnings     No comments   

Issue

I have several checkboxes that I use for display purposes of 'true' and 'false'. Each one will show me the above warning (I made the warning more generic for the purposes of searching. In reality, it reads @Model.Service_Request_Information.Servicelead, etc, instead of @Model.property)

<input class="custom-control-input" type="checkbox" checked="@item.Servicelead" disabled />

I have read that it is okay to write razor code like this, and the HTML will insert/leave out 'checked' from the attributes depending on the value. It works fantastically for how I want it, and it doesn't prevent my code from compiling. So, any ideas on why I am getting this warning?


Solution

Razor will render a boolean attribute if the expression you pass to it evaluates to true. If the expression evaluates to false, the attribute is not rendered at all. That is the Razor feature you are using in your example.

In HTML, valid values for the checked attribute are an empty string or "checked" (Specs) i.e. checked or checked="checked". Visual Studio reports HTML errors as warnings by default, which is what you are seeing. You can either ignore it, turn HTML validation off:

Tools > Options > Text Editor > Html > Validation

Or you can use a ternary expression as demonstrated by other answers:

@(item.Servicelead? "checked" : "")


Answered By - Mike Brind
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing