[Solved] ASP.Net Core MVC: NullReference Error on Model property

saigkill
 
on Dec 23, 2022 10:11 PM
546 Views

Hello Forum,

Currently I'm trying to create a contact form in my ASP.NET Core MVC Blog.

For realizing this, i followed ASP.Net Core Razor Pages: Contact Us Form.

Currently i have that code: My PageModel (cshtml.cs):

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using MannsBlog.Models;
using MannsBlog.Services;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace MannsBlog.Views.Root
{    
    public class ContactModel : PageModel
    {        
        private IConfiguration _configuration;
        
        private GoogleCaptchaService _captcha;
        
        private IMailService _mailService;

        private ILogger<ContactModel> _logger;
      
        public string? Message { get; set; }
       
        public void IndexModel(IConfiguration configuration, GoogleCaptchaService captcha, IMailService mailService, ILogger<ContactModel> logger)
        {
            _configuration = configuration;
            _captcha = captcha;
            _mailService = mailService;
            _logger = logger;
        }
        
        public void OnGet()
        {
        }
        
        public async Task OnPostSubmit(ContactFormModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var spamState = VerifyNoSpam(model);
                    if (!spamState.Success)
                    {
                        _logger.LogError("Spam detected. Break submitting proces..");
                        this.Message = "Spam detected. Sorry";
                    }

                    // Captcha
                    if (await _captcha.Verify(model.Recaptcha))
                    {
                        this.Message = "Recaptcha solved. That are good news.";
                        if (await _mailService.SendMailAsync("ContactTemplate.txt", model.Name, model.Email, model.Subject, model.Body, model.Attachment))
                        {
                            _logger.LogInformation("Captcha verified. Sent mail.");
                            this.Message = "Email sent.";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to send email from contact page", ex);
            }
        }

        // Brute Force getting rid of my worst emails
        private SpamState VerifyNoSpam(ContactFormModel model)
        {
            var tests = new string[]
            {
        "improve your seo",
        "improved seo",
        "generate leads",
        "viagra",
        "your team",
        "PHP Developers",
        "working remotely",
        "google search results",
        "link building software",
            };

            if (tests.Any(t =>
            {
                return new Regex(t, RegexOptions.IgnoreCase).Match(model.Body).Success;
            }))
            {
                return new SpamState() { Reason = "Spam Email Detected. Sorry." };
            }

            return new SpamState() { Success = true };
        }
    }
}

My Page (cshtml):

@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using System.Net.Http
@using Microsoft.Extensions.Configuration;
@using Newtonsoft.Json.Linq
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.JSInterop
@using Microsoft.AspNetCore.Mvc.Localization
@using MannsBlog.Models
@inject IConfiguration _config
@inject IViewLocalizer _localizer
@model MannsBlog.Views.Root.ContactModel

@section styles {
    <link href="/css/contact.css" rel="stylesheet" />
    <style>
        .multiline {
            margin-top: 60px;
            width: 100%;
        }
    </style>
}

@section Scripts{
    <environment include="Development">
        <script type="text/javascript" src="~/lib/tinymce/tinymce.js"></script>
        <script type="text/javascript">
            tinymce.init({ selector: 'textarea', width: 300 });
        </script>
    </environment>
    <environment exclude="Development">
        <script type="text/javascript" src="~/lib/tinymce/tinymce.min.js"></script>
        <script type="text/javascript">
            tinymce.init({ selector: 'textarea', width: 300 });
        </script>
    </environment>
}

@{
    ViewBag.Title = _localizer["viewbag-title"];
    ViewBag.PageName = _localizer["viewbag-pagename"];
    ViewBag.PageBlurb = _localizer["viewbag-pageblurp"];
    ViewBag.PageImage = "/img/headers/code2.jpg";
}

<form method="post" enctype="multipart/form-data">
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td style="width: 80px">Name:</td>
            <td><input type="text" name="Name" /></td>
        </tr>
        <tr>
            <td>Subject:</td>
            <td><input type="text" name="Subject" /></td>
        </tr>
        <tr>
            <td>Email:</td>
            <td><input type="text" name="Email" /></td>
        </tr>
        <tr>
            <td valign="top">Body:</td>
            <td><textarea cols="20" rows="10" name="Body"></textarea></td>
        </tr>
        <tr>
            <td>Attachment:</td>
            <td><input type="file" name="Attachment" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Send" asp-page-handler="Submit" /></td>
        </tr>
    </table>
    <br />
    <span style="color:green">@Model.Message</span>
</form>

Currently the NullReferenceError happens by launching the Contact Page on the line with "@Model.Message".

I don’t know, but it feels, that i have forgotten anything.

It would be great, if anyone can spend one eye.

Greetings Sascha

Download FREE API for Word, Excel and PDF in ASP.Net: Download
PrinceG
 
on Dec 28, 2022 05:49 AM
saigkill says:
@model MannsBlog.Views.Root.ContactModel

You are mixing the Core MVC and Core Razor Pages.

The cshtml pages should be inside the Pages folder instead of Views folder.

Refer below article for creating ASP.Net Core Razor Pages project.

Getting started with ASP.Net Core Razor Pages

saigkill
 
on Dec 30, 2022 08:09 AM

Problem is fixed now. The problem was indeed mixing Razor Pages with MVC. If i'm instancing the Contactform Class from the Controller and give it to the Get Method for the page, it works as expected. :-)