Reputation: 3
I have two Class models:
Author.cs
public class Author()
{
public int AuthorID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
[DataType(DataType.MultilineText)]
public string Bio { get; set; }
public virtual ICollection<Blog> Blogs { get; set; }
}
Blog.cs
public class Blog
{
public int BlogID { get; set; }
public int AuthorID { get; set; }
public virtual Author Author { get; set; }
[Required]
public string Title { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
}
Clearly, an Author can have many Blogs now, the problem is in the View of a Blog. if a person writes "~/Blog/Create" I first want to check if there are already any Author Objects. if not, I will redirect them to the "~/Author/Create" first. that's what I have tried to accomplish thus far:
the header of Blog/Create.cshtml:
@model MVCproject.Models.Blog
@{
if (Model.Author == null)
{
Response.Redirect("~/Author/Create");
}
That's the most logical way I can express it, yet the Null Exception is thrown at me, and I don't know to get around this problem. I suspect I have to change "if(Model.Author == null) " statement to something more convenient.
EDIT:
I haven't changed anything in the controller, I left the mvc scaffolding as is.
Upvotes: 0
Views: 257
Reputation: 12334
It's a bad design decision to have any logic in the view. You should perform the redirect in your controller instead.
In your create blog action, if the author is null
just redirect the user to another action:
return RedirectToAction("Create", "Author");
Upvotes: 2