This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I got null reference exception when i trying to view data from table for actually logged user - Klient_has_sklep and if that user isnt signed with Sklep table.
When i viewing data for user who is signed with Sklep table everything is ok.
I think problem is in Controller with viewModel
This is my controller
public ActionResult Index(int? id)
{
var viewModel = new Klient_has_SklepIndexData();
viewModel.Klients = db.Klients
.OrderBy(i => i.Nazwisko);
UserManager UM = new UserManager();
int idZalogowanego = UM.GetUserID(User.Identity.Name);
ViewBag.idzal = idZalogowanego;
viewModel.Klient_has_Skleps = viewModel.Klients.Where(i => i.SYSUserID == idZalogowanego).Single().Klient_has_Sklep;
return View(viewModel);
}
This is my view
#model Sklepy.Models.ViewModel.Klient_has_SklepIndexData
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.idzal.</h2>
<h2>Twoje zniżki w sklepach</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>asd</th>
</tr>
#if (Model != null)
{
#foreach (var item in Model.Klient_has_Skleps)
{
<tr>
<td>#item.Znizka1</td>
</tr>
}
}
</table>
This is my Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sklepy.Models.DB;
namespace Sklepy.Models.ViewModel
{
public class Klient_has_SklepIndexData
{
public IEnumerable<Klient> Klients { get; set; }
public IEnumerable<Klient_has_Sklep> Klient_has_Skleps {get; set;}
}
}
Klient class code
public partial class Klient
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Klient()
{
this.Klient_has_Sklep = new HashSet<Klient_has_Sklep>();
}
public int KlientID { get; set; }
public int SYSUserID { get; set; }
public string Imię { get; set; }
public string Nazwisko { get; set; }
public string Adres { get; set; }
public string Telefon { get; set; }
public string Email { get; set; }
public virtual SYSUser SYSUser { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Klient_has_Sklep> Klient_has_Sklep { get; set; }
}
Create your ViewModel as shown below. I made modification to make default initialization with List.
public class Klient_has_SklepIndexData
{
public IList<Klient> Klients { get; set; }
public IList<Klient_has_Sklep> Klient_has_Skleps { get; set; }
public Klient_has_SklepIndexData()
{
Klients = new List<Klient>();
Klient_has_Skleps = new List<Klient_has_Sklep>();
}
}
And your Action Code.
public ActionResult Index(int? id)
{
var viewModel = new Klient_has_SklepIndexData();
viewModel.Klients = db.Klients
.OrderBy(i => i.Nazwisko).ToList();
UserManager UM = new UserManager();
int idZalogowanego = UM.GetUserID(User.Identity.Name);
ViewBag.idzal = idZalogowanego;
var skelp = viewModel.Klients.FirstOrDefault(i => i.SYSUserID == idZalogowanego);
if(skelp != null){
if(skelp.Klient_has_Sklep != null){
viewModel.Klient_has_Skleps = skelp.Klient_has_Sklep.ToList();
}
}
return View(viewModel);
}
Related
im learning blazor and wanted to build some small dynamic form generator
i known that there is already something like VxFormGenerator but wanted to learn by myself a bit - at least for simple forms purposes.
so i have it like this:
DynamicFormsComponent:
<EditForm Model = "#Params" OnValidSubmit="OnValidSubmit">
<DataAnnotationsValidator/>
#if(Params != null ) #foreach (var field in Params.FormFields)
{
<div class="mb-3">
<label for= "#field.Id">#field.Label :</label>
#switch (field.Type)
{
case FormFieldType.Text:
{
<InputText id="#field.Id" #bind-Value="#field.StrValue" placeholder="#field.PlaceHolder" class="form-control"></InputText>
break;
}
case FormFieldType.Number:
{
<InputNumber id="#field.Id" #bind-Value="#field.IntValue" placeholder="#field.PlaceHolder" class="form-control"> ></InputNumber>
break;
}
case FormFieldType.Date:
{
<InputDate id="#field.Id" #bind-Value="#field.DateValue" placeholder="#field.PlaceHolder" class="form-control"></InputDate>
break;
}
default:
{
break;
}
}
</div>
}
<ValidationSummary></ValidationSummary>
<button type="submit" class="btn btn-primary">#Params?.SendButtonText</button>
public partial class DynamicFormComponent:ComponentBase
{
[Parameter]
public DynamicFormParams Params { get; set; } = new DynamicFormParams();
[Parameter]
public EventCallback<DynamicFormParams> OnValidSubmitCallback { get; set; }
void OnValidSubmit()
{
Console.WriteLine("onValidSubmit");
if (OnValidSubmitCallback.HasDelegate ) OnValidSubmitCallback.InvokeAsync(Params);
//NavigationManager.navigateto.....
}
}
public class DynamicFormParams
{
public List<DynamicFormField> FormFields { get; set; } = new List<DynamicFormField>();
public string FormTitle { get; set; } = string.Empty;
public string SendButtonText { get; set; } = "Send";
}
public class DynamicFormField
{
public string? Label { get; set; }
public string Id { get; set; } = Guid.NewGuid().ToString();
public string PlaceHolder { get; set; } = string.Empty;
public FormFieldType? Type { get; set; }
public string? StrValue { get; set; }
public int? IntValue { get; set; }
public DateTime? DateValue { get; set; }
}
public enum FormFieldType
{
Text,
Number,
Date
}
so the usage would be
<DynamicFormComponent Params="#p" OnValidSubmitCallback=#onChildFormSubmit ></DynamicFormComponent>
DynamicFormParams p = new DynamicFormParams()
{
FormTitle = "test form Title",
SendButtonText = "Wyślij",
FormFields = new List<DynamicFormField>()
{
new DynamicFormField()
{
Label="testLabelStr",
Id="anyid-notGuId",
StrValue="a",
PlaceHolder="asdadsad",
Type=FormFieldType.Text
},
new DynamicFormField()
{
Label="testLabelInt",
Type=FormFieldType.Number,
PlaceHolder="enter nr"
},
new DynamicFormField()
{
Label="testLabelDate",
Type=FormFieldType.Date,
DateValue=DateTime.Parse("2021-04-01")
}
}
};
private void onChildFormSubmit(DynamicFormParams pp)
{
Console.WriteLine("from local variable");
Console.WriteLine(JsonSerializer.Serialize(p));
Console.WriteLine("from event arg");
Console.WriteLine(JsonSerializer.Serialize(pp));
}
and the question is:
how with this approach i can use form validation ?
i have no clasic'model' so probably would need something like add 'list of validators ' to my DynamicFormField class
and somehow force DataAnnotationsValidator to use this list ? is it possible withoud clasic 'model' and 'data annotations attributes' on it ?
thanks and regards
The only way to validate form without a model is to use the Blazorise validation system. https://blazorise.com/docs/components/validation.
PS. I'm a Blazorise creator.
My view model as
public class StudViewModel
{
public StudLineViewModel()
{
StudLine = new List<CreateReqLineViewModel>();
}
public StudheaderViewModel StudHeader { get; set; }
public List<StudLineViewModel> StudLine { get; set; }
}
public class StudheaderViewModel
{
public int Roll_no { get; set; }
public DateTime? birthday_date { get; set; }
}
public class StudLineViewModel
{
public int Sub_Id { get; set; }
public double marks { get; set; }
}
var MainVMObj = new StudViewModel();
var StudHeaderObj = new StudheaderViewModel ();
StudHeaderObj.Roll_no =1;
StudHeaderObj.birthday_date =null;
MainVMObj.StudHeader = StudHeaderObj ;
MainVMObj.StudLine =null;
return Partialview("StudInfo",MainVMObj );
Code in View
#Html.TextBoxFor(model => model.StudHeader.birthday_date ,new { #class = "InputText", onclick = "javascript:NewCssCal (this.Id,'ddMMMyyyy','arrow','','','','future')" })
expected Result
1. birth day assign null but it show as default date like 01-Jan-0001.
I was debug i found issue at
MainVMObj.StudHeader = StudHeaderObj -->assign object value it make null value to default value. so birth date from null to default(01-01-001)
Please provide the solution
Editors Give the Ans not edit the Post
i was looking for this and tried to fix for couple of days but with no sucess. What wrong im doing in this code? I want to print _Champions
and _SearchEngine as PartialView in Home/Index but it show error.
My HomeController
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult _SearchEngine()
{
SearchLeagueModel searchLeagueModel = new SearchLeagueModel();
searchLeagueModel.MainSelector = "champions";
return PartialView("_SearchEngine", searchLeagueModel);
}
public ActionResult _SearchEngine(SearchLeagueModel searchLeagueModel)
{
if (searchLeagueModel.MainSelector == "champions")
{
return RedirectToAction("_Champions", searchLeagueModel);
}
else return View();
}
[HttpPost]
public ActionResult _Champions(SearchLeagueModel searchLeagueModel)
{
string chooser = searchLeagueModel.MainSelector;
string selector;
if (searchLeagueModel.MainSelector != null)
{
selector = "filter[name]=" + searchLeagueModel.MainSelector;
}
else
{
selector = "";
}
WebRequest request = WebRequest.Create("https://api.pandascore.co/lol/" + chooser + "?" + selector + "&token=mytoken);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string responseFromServer = reader.ReadToEnd();
List<ChampionsModel> champions = JsonConvert.DeserializeObject<List<ChampionsModel>>(responseFromServer);
return PartialView("_Champions", champions);
}
//other views
}
My IndexModelView
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace LeagueAPI.Models
{
public class IndexModelView
{
public IndexModelView()
{
ChampionsList = new ChampionsModel();
Searcher = new SearchLeagueModel();
}
public ChampionsModel ChampionsList { get; set; }
public SearchLeagueModel Searcher { get; set; }
}
public class ChampionsModel
{
public List<string> videogame_versions { get; set; }
public double spellblockperlevel { get; set; }
public double spellblock { get; set; }
public string name { get; set; }
public double mpregenperlevel { get; set; }
public double mpregen { get; set; }
public double mpperlevel { get; set; }
public double mp { get; set; }
public double movespeed { get; set; }
public string image_url { get; set; }
public int id { get; set; }
public double hpregenperlevel { get; set; }
public double hpregen { get; set; }
public double hpperlevel { get; set; }
public double hp { get; set; }
public double critperlevel { get; set; }
public double crit { get; set; }
public string big_image_url { get; set; }
public double attackspeedperlevel { get; set; }
public object attackspeedoffset { get; set; }
public double attackrange { get; set; }
public double attackdamageperlevel { get; set; }
public double attackdamage { get; set; }
public double armorperlevel { get; set; }
public double armor { get; set; }
}
}
My _Champions.cshtml PartialView(made as PartialView)
#using LeagueAPI.Models
#model System.Collections.Generic.List<ChampionsModel>
<fieldset>
<div class="d-flex p-3 w-auto h-auto">
#foreach (var element in #Model)
{
<div class="p-3 flex-lg-wrap">
<div class="card p-2" style="width: 15rem ;">
<img class="card-img-top" src="#Html.DisplayFor(model => element.big_image_url)">
<div class="card-body p-0 m-0">
<h5 class="card-title p-0 m-0 text-center">#Html.DisplayFor(model => element.name)</h5>
<p class="card-text p-0 m-0">DMG/LVL: #Html.DisplayFor(model => element.attackdamageperlevel)</p>
<p class="card-text p-0 m-0">ARMOR/LVL: #Html.DisplayFor(model => element.armorperlevel)</p>
<p class="card-text p-0 m-0">MOVEMENT SPEED: #Html.DisplayFor(model => element.movespeed)</p>
<p class="card-text p-0 m-0">ATTACK RANGE: #Html.DisplayFor(model => element.attackrange)</p>
<a href="/Home/Details"
class="btn btn-primary m-1 "
OnClick="GreetingBtn_Click">More details</a>
</div>
</div>
</div>
}
</div>
</fieldset>
Index View
#model LeagueAPI.Models.IndexModelView
#Html.Action("_SearchEngine", Model.Searcher)
#Html.Action("_Champions", Model.ChampionsList)
Everything else looks standard, in _Layout i have #RenderBody()
My second question is about _Champions Controller. Why when i put IndexModelView indexModelView = new IndexModelView() as parametr and bring necessary changes in code to this ActionResult, the MainSelector is null in that case.
Im still learning, if You can explain whats wrong here i will be thankful. cheers
Try this java Script:-
<script>
function printContent(el){
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById(el).innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
</script>
I would say instead of ActionResults rather use PartialViewResult on both actions _Champions and _SearchEngine
[HttpPost]
public PartialViewResult _Champions(SearchLeagueModel searchLeagueModel)
{
return PartialView("_Champions", champions);
}
And then from the index view Render those action like below:
#model LeagueAPI.Models.IndexModelView
<div>
#Html.RenderAction("_Champions");
#Html.RenderAction("_SearchEngine");
</div>
How to pass an array from mvc controller to java script in HTML.CS page
This is My Model
public class Event
{
public int ID { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string Description { get; set; }
}
And My Controller
public IActionResult Calendar()
{
ViewData["User"] = user;
ViewData["Events"] = events;
return View();
}
Hope it helps
In controller:
public IActionResult Calendar()
{
var users = db.Users;
var events = db.Events.ToList();
ViewData["events"] = events; // Send this list to the view
return View(users .ToList());
}
In view:
#model IEnumerable<Models.User>
#{
var events= (List<Event>) ViewData["events"]; // Cast events to list
}
#foreach (var e in #events) // Print the list
{
#Html.Label(e.Description);
}
<table>
...
#foreach (var item in Model)
{
... // each user in here in item
}
</table>
I am building a web application in ASP.NET MVC. I have a comment page where comments are displayed in a list with the latest to oldest and also have a form at the bottom where a user can post new comments.
Form entries should also be highlighted in addition to having the page displaying the latest comments.
Whats the best way to do this, where displayed data and a post form are on the same page?
Is it possible to do this without ajax as well ?
--Code extract--
class CommentsViewModel
{
public IList<Comment> comments { get; set; }
public Comment comment { get; set; }
public SelectList commentCategories { get; set; }
}
class Comment
{
[Required]
public string commentData { get; set; }
[Required]
public int? commentCategory { get; set; }
}
class Comments : Controller
{
public ActionResult Index()
{
Site db = new Site();
CommentsViewModel commenstVm = new
{
comments = db.GetComments(),
comment = new Comment(),
commentCategories = db.GetCommentCategories()
};
return View(commentsVm);
}
[HttpPost]
public ActionResult AddNewComment(CommentsViewModel commentVm)
{
Site db = new Site();
if (!ModelState.IsValid)
{
return View("Index", commentVm);
}
db.AddComment(commentVm.comment);
return RedirectToAction("Index");
}
}
Here's a basic View and the Controller that you can use as a starting point.
Model and ViewModel:
public class CommentsViewModel
{
public IList<Comment> comments { get; set; }
public CommentsViewModel()
{
comments = new List<Comment>();
}
}
public class Comment
{
[Required]
public string commentData { get; set; }
/** Omitted other properties for simplicity */
}
View:
#using (#Html.BeginForm("Index", "Comments"))
{
#Html.TextBoxFor(t => t.comment.commentData)
#Html.ValidationMessageFor(t=> t.comment.commentData, "", new {#class = "red"})
<button name="button" value="addcomment">Add Comment</button>
}
#foreach (var t in Model.comments)
{
<div>#t.commentData</div>
}
Controller:
public class CommentsController : Controller
{
/** I'm using static to persist data for testing only. */
private static CommentsViewModel _viewModel;
public ActionResult Index()
{
_viewModel = new CommentsViewModel();
return View(_viewModel);
}
[HttpPost]
public ActionResult Index(Comment comment)
{
if (ModelState.IsValid)
{
_viewModel.comments.Add(
new Comment() {commentData = comment.commentData});
return View("Index", _viewModel);
}
return RedirectToAction("Index");
}
}