[HttpPost]
public ActionResult Create(Playlist playlist)
{
if (ModelState.IsValid)
{
if (Session["Playlist"] != null)
{
List<int> musicIds = new List<int>();
musicIds = Session["Playlist"] as List<int>;
if (musicIds.Count > 0)
{
UserProfileRepository UserProfileRepository = new UserProfileRepository(db);
string Name = this.User.Identity.Name;
UserProfile User = UserProfileRepository.getModelByName(Name);
playlist.UserId = User.UserId;
db.Playlists.Add(playlist);
db.SaveChanges();
foreach (var item in musicIds)
{
Music music = db.Musics.Find(item);
/*
* Error in the line below, it says:
* Object reference not set to an instance of an object.
* */
playlist.Musics.Add(music);
}
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
return View(playlist);
}
Hello everyone, can someone tell what is wrong in my code?
I cant seem to figure out why it says " Object reference not set to an instance of an object. " when both playlist and music are instantiated.
Thanks in advance!
That would mean that playlist.Musics is null.
You should initialize it in your constructor.
Related
My below view code in View is below
#{
ViewBag.Title = "Student Dashboard";
var StudentRequestTimedt = ViewBag.StudentRequestTime as DataTable;
if (StudentRequestTimedt != null)
{
var StudentRequestTime = StudentRequestTimedt.AsEnumerable().Select(t => new
{
StudentRequestId = t.Field<int>("StudentRequestId"),
FromTime = t.Field<string>("FromTime"),
ToTime = t.Field<string>("ToTime"),
}).ToList();
}
else
{ var StudentRequestTime = ""; }
}
if (StudentRequestTime != "")
{
var StudentRequestTimecount = StudentRequestTime.Where(d => d.StudentRequestId == StudentRequestId).ToList();
}
On writting this I am getting error as StudentRequestTime doesnot exist in the current context.
This issue comes in case I am returning ViewBag.StudentRequestTime as null from controller side
My controller side code is as
if (GetData.Tables[1].Rows.Count > 0 && GetData.Tables[0].Rows.Count > 0)
{
ViewBag.StudentRequestTime = GetData.Tables[1];
}
else
{
ViewBag.StudentRequestTime = null;
}
return View();
Please Also review this below image, Here I am getting data in multiple viewbag in this case how can I manage? var StudentRequestTime is null or empty
How can I handle this issue ?
Updated code resolved my issue
Old code of controller
if (GetData.Tables[1].Rows.Count > 0 && GetData.Tables[0].Rows.Count > 0)
{
ViewBag.StudentRequestTime = GetData.Tables[1];
}
else
{
ViewBag.StudentRequestTime = null;
}
return View();
New Code of controller
ViewBag.StudentRequestTime = GetData.Tables[1];
On ViewSide
Consider this example:
if (eyeColor == EyeColor.Green)
{
// greenEyeColorFound has been declared *in this if statement*,
// so it only exists *within this if statement*
var greenEyeColorFound = true;
}
// this will fail. greenEyeColorFound was declared *in the first if statement*,
// how can the if statement below be aware of it's existence?
if (greenEyeColorFound == true)
{
Debug.WriteLine("Found a person with green eyes!");
}
greenEyeColorFound is locally scoped to the first if statement. Only code within that if statement can be aware of it's existence.
To get my example to work, greenEyeColorFound should be accessible by both ifs, which can be achieved by placing it's declaration outside of both ifs:
// this is now declared *outside* of the two if statements,
// so both are now aware of it and can access it's value.
var greenEyeColorFound = false;
if (eyeColor == EyeColor.Green)
{
greenEyeColorFound = true;
}
// presto, this now works
if (greenEyeColorFound == true)
{
Debug.WriteLine("Found a person with green eyes!");
}
This is the exact issue you are having with StudentRequestTime. Declare it once outside of the ifs, then just set it's value in your if/else statements.
Since we're at it, I wouldn't use ViewBag at all, let alone have it carry DataTables over to the Razor side. I would use viewmodels (read "Accessing Your Model's Data from a Controller" over at Microsoft ASP.NET MVC docs to see how this works, in particular section "Strongly Typed Models and the #model Keyword") which are much cleaner and maintainable.
You can easily refactor your existing code to use viewmodels using the steps below:
1) Create a class, let's name it StudentRequestTimeViewModel:
public class StudentRequestTimeViewModel
{
public int StudentRequestId { get; set; }
public string FromTime { get; set; }
public string ToTime { get; set; }
}
2) In your controller, populate a List<StudentRequestTimeViewModel>:
var studentRequestTimes = new List<StudentRequestTimeViewModel>();
if (GetData.Tables[1].Rows.Count > 0 && GetData.Tables[0].Rows.Count > 0)
{
// populate studentRequestTimes here
}
// return the view, passing in studentRequestTimes as our model
return View(studentRequestTimes);
3) Your Razor then becomes:
/* your model is declared as "#model",
but is accessed as "Model". */
#model List<StudentRequestTimeViewModel>
#if (Model != null && Model.Count > 0)
{
/* your List<StudentRequestTimeViewModel> Model is not null or empty */
foreach(var studentRequestTime in Model)
{
<p>Student with ID #studentRequestTime.StudentRequestId is here.</p>
}
}
else
{
/* your List<StudentRequestTimeViewModel> Model is null or empty */
}
I am populating a list based on data returned from a stored procedure, this first occurs in the SpecificArea ActionResult:
public ActionResult SpecificArea(ModelCallDetails call, int id = 0 )
{
ReturnSpecificAreas(call, id);
return PartialView("SpecificArea", listCallDetails);
}
When the list is displayed each row is an actionlink, which will sends the data to the SpecificAreaWorker:
[HttpGet]
public ActionResult SpecificAreaWorker(ModelCallDetails call, int id)
{
TempData["StringOfIds"] = StringOfIds;
ReturnSpecificAreas(call, id);
if (ResponseMessage == "Successful")
{
return PartialView("SpecificArea", listCallDetails);
}
else
{
return RedirectToAction("ViewCall");
}
}
I am wanting to collect the id of each row that is clicked and store them in a list in the model so that I can create a string of id's. However, each time a row in the table is clicked it refreshes the model, and I no longer have a list of ids anymore.
public void ReturnSpecificAreas(ModelCallDetails call, int id)
{
SelectedAffectedServiceID = id;
call.AffectedServiceList.Add(SelectedAffectedServiceID);
foreach (int item in call.AffectedServiceList)
{
if (TempData["StringOfIds"] != null)
{
StringOfIds = TempData["StringOfIds"].ToString();
StringOfIds += string.Join(",", call.AffectedServiceList.ToArray());
}
else
{
StringOfIds += string.Join(",", call.AffectedServiceList.ToArray());
}
}
I have tried to mantain the data in tempdata, but can't manage to execute this -will the tempdata refresh each time the actionlink is clicked? Is there a better way to achieve this?
I believe you are using MVC5? If so, use
System.Web.HttpContext
This gets current request
to save....
System.Web.HttpContext.Current.Application["StringOfIds"] = StringOfIds; //Saves global
System.Web.HttpContext.Current.Session["StringOfIds"] = StringOfIds; //Saves Session
To retrieve...
StringOfIds = (string) System.Web.HttpContext.Current.Application ["StringOfIds"]; //Retrieves from global memory
StringOfIds = (string) System.Web.HttpContext.Current.Session ["StringOfIds"]; //retrieves from session memory
Good luck.
How to save mixed data in multiple tables if is checked checkbox:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "rID,AgentID,karta_br,Datum,patnikID,stanicaOD,stanicaDO,cena,povratna")] tbl_rezervacii tbl_rezervacii)
{
if (ModelState.IsValid)
{
if (tbl_rezervacii.povratna != true)
{
db.tbl_rezervacii.Add(tbl_rezervacii);
db.SaveChanges();
}
else
{
tbl_rezervacii rezervacii = new tbl_rezervacii()
{
???????????????????????
};
db.tbl_rezervacii.Add(rezervacii);
db.SaveChanges();
tbl_povratni povratni = new tbl_povratni()
{
???????????????????????
};
db.tbl_povratni.Add(povratni);
db.SaveChanges();
}
This is code in the controller, and I need to mix data from two forms, and save to two tables, I need something like this, and now my problem is just in else section of implementation.
I make application for Bus Ticket system, and i need this if is checked return way checkbox to add: rID (related with first table tbl_rezervacii), date of returning and relation of returning, include same agent id, price, etc. data which is saved in first tbl_rezervacii table.
MODIFIED CONTROLLER CODE:
public ActionResult Create([Bind(Include = "rID,AgentID,karta_br,Datum,patnikID,stanicaOD,stanicaDO,cena,povratna")] tbl_rezervacii tbl_rezervacii )
{
if (ModelState.IsValid)
{
if (tbl_rezervacii.povratna != true)
{
db.tbl_rezervacii.Add(tbl_rezervacii);
db.SaveChanges();
}
else
{
tbl_rezervacii rezervacii = new tbl_rezervacii()
{
AgentID = tbl_rezervacii.AgentID,
karta_br = tbl_rezervacii.karta_br,
Datum = tbl_rezervacii.Datum,
patnikID = tbl_rezervacii.patnikID,
stanicaOD = tbl_rezervacii.stanicaOD,
stanicaDO = tbl_rezervacii.stanicaDO,
cena = tbl_rezervacii.cena,
povratna = tbl_rezervacii.povratna
};
db.tbl_rezervacii.Add(rezervacii);
//db.SaveChanges();
var rows = db.SaveChanges();
tbl_povratni povratna = new tbl_povratni()
{
rezID = rezervacii.rID,
AgentID = rezervacii.AgentID,
karta_br = rezervacii.karta_br,
DatumP = **tbl_povratni.DatumP**,
patnikID = rezervacii.patnikID,
stanicaPOD = **tbl_povratni.stanicaPOD**,
stanicaPDO = **tbl_povratni.stanicaPDO**,
};
db.tbl_povratni.Add(povratna);
db.SaveChanges();
}
ViewBag.AgentID = new SelectList(db.tbl_agenti, "aID", "agent_ime", tbl_rezervacii.AgentID);
ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "ime", tbl_rezervacii.patnikID);
ViewBag.stanicaOD = new SelectList(db.tbl_stanici, "sID", "stanica", tbl_rezervacii.stanicaOD);
ViewBag.stanicaDO = new SelectList(db.tbl_stanici, "sID", "stanica", tbl_rezervacii.stanicaDO);
ViewBag.stanicaPOD = new SelectList(db.tbl_stanici, "sID", "stanica", tbl_rezervacii.tbl_povratni.stanicaPOD);
ViewBag.stanicaPDO = new SelectList(db.tbl_stanici, "sID", "stanica", tbl_rezervacii.tbl_povratni.stanicaPDO);
return View(tbl_rezervacii);
}
return RedirectToAction("Index");
}
How to take data from secondary form and save together in second table?
So, if checkbox is checked, you want to save data into two tables and use primary key of first table (rID) in second table? If rID is auto increment, It will be updated by EF with the value assigned by the database.
tbl_rezervacii rezervacii = new tbl_rezervacii()
{
AgentID = tbl_rezervacii.AgendID,
karta_br = tbl_rezervacii.karta_br
// and so on...
};
db.tbl_rezervacii.Add(rezervacii);
var rows = db.SaveChanges(); // optional, rows will be > 0 if saved successfully.
tbl_povratni povratni = new tbl_povratni()
{
// if rID is auto increment
rID = rezervacii.rID,
// and so on...
};
db.tbl_povratni.Add(povratni);
db.SaveChanges();
I Create A News Site With MVC5 But I Have Problem .
in Model i Create A Repository Folder And in this i Create Rep_Setting for
Connect to Tbl_Setting in DataBase .
public class Rep_Setting
{
DataBase db = new DataBase();
public Tbl_Setting Tools()
{
try
{
var qGetSetting = (from a in db.Tbl_Setting
select a).FirstOrDefault();
return qGetSetting;
}
catch (Exception)
{
return null;
}
}
}
And i Create a Rep_News for Main Page .
DataBase db = new DataBase();
Rep_Setting RSetting = new Rep_Setting();
public List<Tbl_News> GetNews()
{
try
{
List<Tbl_News> qGetNews = (from a in db.Tbl_News
where a.Type.Equals("News")
select a).OrderByDescending(s => s.ID).Skip(0).Take(RSetting.Tools().CountNewsInPage).ToList();
return qGetNews;
}
catch (Exception ex)
{
return null;
}
}
But This Code Have Error to Me
OrderByDescending(s=>s.ID).Skip(0).Take(RSetting.Tools().CountNewsInPage).ToList();
Error :
Error 18 'System.Linq.IQueryable<NewsSite.Models.Domain.Tbl_News>' does
not contain a definition for 'Take' and the best extension method overload
'System.Linq.Queryable.Take<TSource>(System.Linq.IQueryable<TSource>, int)' has
some invalid arguments
E:\MyProject\NewsSite\NewsSite\Models\Repository\Rep_News.cs 50 52 NewsSite
How i Resolve it ?
Try it this way. The plan of debugging is to split your execution, this also makes for a more reusable method in many cases. And a good idea is to avoid using null and nullables if you can, if you use them "on purpose" the you must have a plan for them.
DataBase db = new DataBase();
Rep_Setting RSetting = new Rep_Setting();
public List<Tbl_News> GetNews()
{
int skip = 0;
Tbl_Setting tools = RSetting.Tools();
if(tools == null){ throw new Exception("Found no rows in the database table Tbl_Setting"); }
int? take = tools.CountNewsInPage;//Nullable
if(!take.HasValue)
{
// Do you want to do something if its null maybe set it to 0 and not null
take = 0;
}
string typeStr = "News";
List<Tbl_News> qGetNews = (from a in db.Tbl_News
where a.Type.Equals(typeStr)
select a).OrderByDescending(s => s.ID).Skip(skip).Take(take.Value);
return qGetNews.ToList();
}
if qGetNews is a empty list you now don't break everything after trying to iterate on it, like your return null would. instead if returning null for a lit return a new List<>() instead, gives you a more resilient result.
So I said reusable method, its more like a single action. So you work it around to this. Now you have something really reusable.
public List<Tbl_News> GetNews(string typeStr, int take, int skip = 0)
{
List<Tbl_News> qGetNews = (from a in db.Tbl_News
where a.Type.Equals(typeStr)
select a).OrderByDescending(s => s.ID).Skip(skip).Take(take);
return qGetNews.ToList();
}
Infact you shjould always try to avoid returning null if you can.
public class Rep_Setting
{
DataBase db = new DataBase();
public Tbl_Setting Tools()
{
var qGetSetting = (from a in db.Tbl_Setting
select a).FirstOrDefault();
if(qGetSetting == null){ throw new Exception("Found no rows in the database table Tbl_Setting"); }
return qGetSetting;
}
}
I am new to the dependency injection pattern and I am having issues getting a new instance of a class from container.Resolve in tinyioc it just keeps returning the same instance rather than a new instance. Now for the code
public abstract class HObjectBase : Object
{
private string _name = String.Empty;
public string Name
{
get
{
return this._name;
}
set
{
if (this._name == string.Empty && value.Length > 0 && value != String.Empty)
this._name = value;
else if (value.Length < 1 && value == String.Empty)
throw new FieldAccessException("Objects names cannot be blank");
else
throw new FieldAccessException("Once the internal name of an object has been set it cannot be changed");
}
}
private Guid _id = new Guid();
public Guid Id
{
get
{
return this._id;
}
set
{
if (this._id == new Guid())
this._id = value;
else
throw new FieldAccessException("Once the internal id of an object has been set it cannot be changed");
}
}
private HObjectBase _parent = null;
public HObjectBase Parent
{
get
{
return this._parent;
}
set
{
if (this._parent == null)
this._parent = value;
else
throw new FieldAccessException("Once the parent of an object has been set it cannot be changed");
}
}
}
public abstract class HZoneBase : HObjectBase
{
public new HObjectBase Parent
{
get
{
return base.Parent;
}
set
{
if (value == null || value.GetType() == typeof(HZoneBase))
{
base.Parent = value;
}
else
{
throw new FieldAccessException("Zones may only have other zones as parents");
}
}
}
private IHMetaDataStore _store;
public HZoneBase(IHMetaDataStore store)
{
this._store = store;
}
public void Save()
{
this._store.SaveZone(this);
}
}
And the derived class is a dummy at the moment but here it is
public class HZone : HZoneBase
{
public HZone(IHMetaDataStore store)
: base(store)
{
}
}
Now since this is meant to be an external library I have a faced class for accessing
everything
public class Hadrian
{
private TinyIoCContainer _container;
public Hadrian(IHMetaDataStore store)
{
this._container = new TinyIoCContainer();
this._container.Register(store);
this._container.AutoRegister();
}
public HZoneBase NewZone()
{
return _container.Resolve<HZoneBase>();
}
public HZoneBase GetZone(Guid id)
{
var metadataStore = this._container.Resolve<IHMetaDataStore>();
return metadataStore.GetZone(id);
}
public List<HZoneBase> ListRootZones()
{
var metadataStore = this._container.Resolve<IHMetaDataStore>();
return metadataStore.ListRootZones();
}
}
However the test is failing because the GetNewZone() method on the Hadrian class keeps returning the same instance.
Test Code
[Fact]
public void ListZones()
{
Hadrian instance = new Hadrian(new MemoryMetaDataStore());
Guid[] guids = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
int cnt = 0;
foreach (Guid guid in guids)
{
HZone zone = (HZone)instance.NewZone();
zone.Id = guids[cnt];
zone.Name = "Testing" + cnt.ToString();
zone.Parent = null;
zone.Save();
cnt++;
}
cnt = 0;
foreach (HZone zone in instance.ListRootZones())
{
Assert.Equal(zone.Id, guids[cnt]);
Assert.Equal(zone.Name, "Testing" + cnt.ToString());
Assert.Equal(zone.Parent, null);
}
}
I know its probably something simple I'm missing with the pattern but I'm not sure, any help would be appreciated.
First, please always simplify the code to what is absolutely necessary to demonstrate the problem, but provide enough that it will actually run; I had to guess what MemoryMetaDataStore does and implement it myself to run the code.
Also, please say where and how stuff fails, to point others straight to the issue. I spent a few minues figuring out that the exception I was getting was your problem and you weren't even getting to the assertions.
That said, container.Resolve<HZoneBase>() will always return the same instance because that's how autoregistration in TinyIoC works - once an abstraction has been resolved, the same instance is always returned for subsequent calls.
To change this, add the following line to the Hadrian constructor:
this._container.Register<HZoneBase, HZone>().AsMultiInstance();
This will tell the container to create a new instance for each resolution request for HZoneBase.
Also, Bassetassen's answer about the Assert part is correct.
In general, if you want to learn DI, you should read Mark Seemann's excellent book "Dependency Injection in .NET" - not quite an easy read as the whole topic is inherently complex, but it's more than worth it and will let you get into it a few years faster than by learning it on your own.
In your assert stage you are not incrementing cnt. You are also using the actual value as the expected one in the assert. This will be confusing, becuase it says something is excpected when it actually is the actual value that is returned.
The assert part should be:
cnt = 0;
foreach (HZone zone in instance.ListRootZones())
{
Assert.Equal(guids[cnt], zone.Id);
Assert.Equal("Testing" + cnt.ToString(), zone.Name);
Assert.Equal(null, zone.Parent);
cnt++;
}