0

I am currently trying to program a forgot password page where the user enter their username, their email address and a message which will be sent to the administrator of the site. Want I want is the following: After the user clicks on the button the username and the email address should be checked if they are associated. (Those values are saved in my database) I managed to programm everything but I have a problem which I cannot solve. Everytime the Razor engine renders the page I'll get a NullReferenceException was unhandled by user code. I know why this is happening but as I said I cannot fix this.

Here is the code:

@model MvcApplication1.ViewModels.ContactAdminViewModel
@using MvcApplication1.Queries
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" />
    <title>SendMail</title>
</head>
<body>
    @using (Html.BeginForm("SendMail", "ContactAdmin", FormMethod.Post))
    {
        @Html.ValidationSummary(true) 
        <div>
            <p>
                @Html.LabelFor(m => m.username, "username")
                @Html.EditorFor(m => m.username)
                <p>
                    @Html.ValidationMessageFor(m => m.username)
                </p>
            </p>
            <p>
                @Html.LabelFor(m => m.email, "email")
                @Html.EditorFor(m => m.email)
                <p>
                    @Html.ValidationMessageFor(m => m.email)
                </p>
            </p>
            <p>
                @Html.LabelFor(m => m.message, "Your message")
                <p>
                    @Html.TextAreaFor(m => m.message, new { cols = "35", rows = "10", @style = "resize:none" })
                    <p>
                        @Html.ValidationMessageFor(m => m.message)
                    </p>
                </p>
            </p>

            <p>
                <input id="send-mail" type="submit" class="button" value="Send" />
            </p>
        </div>
        
        <script type="text/javascript">
            $(document).ready(function () {
                jQuery('#send-mail').click(function () {
                    @if (@DQL.CheckUsernameAndEmail(Model.username, Model.email))
                    {
                        <text>
                    alert("Your Message will be sent");
                    </text>
                        
                    }

                    else
                    {
                        <text>
                    alert("Your username is not associated with the email adress");
                    </text>
                    }


                });
            });
        </script>

        
    }
</body>
</html>

Any tips on how to solve that problem are highly appreciated :)

EDIT

The DQL.cs is a C# Class where I wrote down all my queries. It's actually the model that is null. I forgot to write that :/ I'm really sorry. Nevertheless here is the code from the DQL.cs which checks if the username is associated with the email address:

    public static bool CheckUsernameAndEmail(string username, string email)
    {
        bool validateUser = false;

        var query = from u in db.User
                    where (u.email.Equals(email) && u.username.Equals(username))
                    select u;

        if (query.Count() != 0)
            validateUser = true;

        return validateUser;
    }

This the Controller code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.ViewModels;
using MvcApplication1.Database_Queries;

namespace MvcApplikation1.Controllers
{
    public class ContactAdminController : Controller
    {
        [HttpGet]
        public ActionResult SendMail()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SendMail(ContactAdminViewModel contactAdmin)
        {

            if (ModelState.IsValid)
            {
                if (DQL.CheckUsernameAndEmail(contactAdmin.username, contactAdmin.email))
                {
                    MvcApplication1.Mail.SendMail.SendForgotPassword(contactAdmin.username, contactAdmin.email, contactAdmin.message);
                    return RedirectToAction("LogIn", "Account");
                }
            }
            else
            {
                ModelState.AddModelError("", "Your username is not associated with the email adress");
                return RedirectToAction("LogIn", "Account");
            }

            return RedirectToAction("LogIn", "Account");
        }

    }
}
2
  • Look at the stack trace. What line is the NullReferenceException getting thrown on? Commented Jun 19, 2013 at 23:14
  • @StriplingWarrior It is the Model that is throwing the NullReferenceException. This happens when I change the Url to localhost:22008/ContactAdmin/SendMail The only thing that I can think of is the following: Because the page is rendered first the model is empty and that's why the Exception is thrown. Commented Jun 19, 2013 at 23:29

1 Answer 1

1

If this is getting a NullReferenceException:

if (@DQL.CheckUsernameAndEmail(Model.username, Model.email))

Then it's either because DQL is null, Model is null, or some code in CheckUsernameAndEmail is throwing that exception. We don't have enough context in this question to know what DQL is, and the population of your model is done in your controller action, which is not posted in this question. Posting CheckUsernameAndEmail's code may also help.

Basically, any time you get NullReferenceException it means you have a null reference.

Update

Thanks for the updated information! If you don't want your Model to be null when executing your Razor view, make sure to add a model to your ViewResult:

[HttpGet]
public ActionResult SendMail()
{
    var model = new ContactAdminViewModel();
    // Populate your model with the appropriate data

    return View(model);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much! Once again I am really sorry that I missed to put the entire code
I tested your answer and it has one bug. Now that I am giving the view the model (which is actually null) I always get the "Your username and email are not associated" alert.
Not sure if this is your confusion, but keep in mind that the Razor template executes once, before the page is loaded. If you want to validate the data you've entered in the page, you'll need JavaScript validation. Your CheckUsernameAndEmail is only run while the page is rendering.
I have to admit that I am really new to ASP.NET and Javascript. Could please post a javascript code that validate after the user entered the data in the page?
That's a bit too big of an ask for this forum, sorry. Your current validation function checks data against a database, which you cannot do directly with JavaScript. You'll either have to add an action to your controller to do the validation and call that with AJAX techniques or just do all validation on the server. Seems like you have a few things to educate yourself on. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.