I have a database with folders where I store the whole path to a folder as a folder_name
so sth. like: //MainFolder/subFolder/folderName
. Im my application I have a Model called Folder
, which represents the folders from db.
Model:
public class Folder
{
[Key]
public string folder_name { get; set; }
[NotMapped]
public string folder_name_short
{
get
{
string shortname = folder_name.Substring(folder_name.LastIndexOf("/"), folder_name.Length - folder_name.LastIndexOf("/")); //System.NullReferenceException here
return shortname;
}
set
{
string shortname = folder_name.Substring(folder_name.LastIndexOf("/"), folder_name.Length - folder_name.LastIndexOf("/"));
this.folder_name = folder_name.Replace(shortname, value);
}
}
}
folder_name_short
isn't mapped because it is only a substring from the whole path, so I don't want to store it twice. Example want I mean:
Console.WriteLine(folder_name) output://MainFolder/subFolder/folderName
Console.WriteLine(folder_name_short) output:/folderName
In my View the user can rename the folder. So I would like to replace the old folder_name_short
to the new one and store the new String in folder_name
View:
.
.
using (Html.BeginForm("Rename", "Folders", FormMethod.Post))
{
@Html.EditorFor(model => model.folder_name_short)
<input type="submit" value="rename folder" id="submit" class="btn btn-default" />
}
.
.
Problem:
The Inputtextbox renders and shows the current Value of folder_name_short
in it. When I change it and click the submit button, I get a System.NullReferenceException
in the Model (as marked in the source code, please scroll to right). I don't understand what is wrong and what changes are needed.
Edit:
when the setter is commented out, the Exception disappear. So maybe the setter is causing the error?
Solution:
use the standard setter and getter for storing the folder_name_short
value, but implement a public get/set method to set the folder_name
in the db and call this method in the controller. So:
[NotMapped]
public string folder_name_short { get; set; }
public string getfolder_name_short()
{
string shortname = folder_name.Substring(folder_name.LastIndexOf("/"), folder_name.Length - folder_name.LastIndexOf("/"));
return shortname;
}
public void setfolder_name_short(string newname)
{
string shortname = folder_name.Substring(folder_name.LastIndexOf("/"), folder_name.Length - folder_name.LastIndexOf("/"));
folder_name = folder_name.Replace(shortname, newname);
}