I’m new to MVC having previously done a lot of numerical programming in C# console applications. I’d like to eventually build web applications that run these same type of programs. My first attempt though has run into difficulties.
This is a very basic application that will take in a number from a form and then calculate the sum of all the numbers between 1 and that number that are divisible by either 3 or 5. I created a simple Model class which contains a variable that will correspond to the input:
namespace MvcDemo.Models
{
public class Values
{
public int Number { get; set; }
}
}
I then created a controller class:
namespace MvcDemo.Controllers
{
public class HomeController : Controller
{
Values v = new Values();
public ActionResult Index()
{ return View(); }
[HttpPost]
public ActionResult Index(int number)
{
v.Number = number;
return View(v);
}
}
}
and finally the View:
@Model MvcDemo.Models.Values
@{ViewBag.Title = "Home Page";}
<h1>Sum of Multiples of 3 & 5</h1>
@using (Html.BeginForm()){
@Html.TextBox("number");
<input type="submit" />
}
@{
int n;
List<int> nums = new List<int>();
int sum = 0;
if(@Model.Number!=null)
{
n = @Model.Number;
}
else
{
n = 10;
}
for (int i = 1; i < n; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
nums.Add(i);
}
}
for (int j = 0; j < nums.Count; j++)
{
sum += nums[j];
}
}
<p>The sum of the factors is: @sum</p>
When I try and run this I get an exception saying “Cannot perform runtime binding on a null reference”. This is referring to my view page where I’m trying to assign n. I’m not quite sure how to get around this.
Also is it bad practice to have the numerical logic within the view class or would this be better within the controller class?
You’re getting an error because the model is null.
If you use a strongly-typed view, you wouldn’t get that error, but since you wrote
@Modelrather than@model, your view is not strongly typed.