insert selected value from drop down by razor mvc - razor

hi, I had aproject and one of my task as to insert selected value from
drop down to DB field by razor mvc. I did my code but no values inserted ,Also the DDL have items from DB well . my project with razor mvc4.
public ActionResult Create()
{
var data = db.Categories.ToList().Distinct();
foreach (var t in data)
{
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
}
ViewBag.Parent = items;
return View();
}
[HttpPost]
public ActionResult Create(Category category, IEnumerable<HttpPostedFileBase> files)
{
if (Request.Files.Count > 0)
{
var uploadedFile = Request.Files[0];
var fileSavePath = "";
var fileName = "";
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/Uploads/" + fileName);
uploadedFile.SaveAs(fileSavePath);
category.Path = "~/App_Data/Uploads/" + fileName;
}
var data = db.Categories.ToList().Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in data)
{
SelectListItem s = new SelectListItem();
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
if (s.Selected)
{ category.Parent_ID = int.Parse(s.Value); }
}
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}

Hi Your code should be something like this. I am assuming that you have model with certain structure. If belo code does not give you a clue then please. Tell how your view and model is and what is your requirement.
Hope this helps.
[HttpPost]
public ActionResult Create(Category category, IEnumerable<HttpPostedFileBase> files)
{
if (Request.Files.Count > 0)
{
var uploadedFile = Request.Files[0];
var fileSavePath = "";
var fileName = "";
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/Uploads/" + fileName);
uploadedFile.SaveAs(fileSavePath);
category.Path = "~/App_Data/Uploads/" + fileName;
}
var data = db.Categories.ToList().Distinct();
//I assume that you need to find the category from db.Caegories which user has selected on the UI and submited the form.
//I assume the parameter category is the one which you want to find from DB.
//category is your model has Parent_Id property which is bound to UI control (ie. dropdown)
var categoryToSave = (from c in data
where c.Cat_ID == category.Parent_ID
select c).firstOrDefault();
if(categoryToSave!=null)
{
//I believe here you want to save this category to some other table.
//Now you have got the category tht user has selected on UI.
//Write the further logic here.....
db.SaveChanges();
}
return RedirectToAction("Index");
}
Regards, Mahesh

you are creating the fresh selectListItem s here in the same loop. You will get seleced == true for any of the item.
May be item, that user has selected on UI (before post) exist in category param if it is your model that is bound to desired dropdown.
I suspect it is a logical error.
Regards, Mahesh

Related

In MVC, pass complex query and view model to session?

I have a view model:
public class UserCollectionView
{
public CardCollection CardCollections { get; set; }
public Card Cards { get; set; }
}
I have a List View Controller:
public ActionResult ViewCollection(int? page)
{
var userid = (int)WebSecurity.CurrentUserId;
var pageNumber = page ?? 1;
int pageSize = 5;
ViewBag.OnePageOfCards = pageNumber;
if (Session["CardCollection"] != null)
{
var paging = Session["CardCollection"].ToString.();
return View(paging.ToPagedList(pageNumber, pageSize));
}
var viewModel = from c in db.Cards
join j in db.CardCollections on c.CardID equals j.CardID
where (j.NumberofCopies > 0) && (j.UserID == userid)
orderby c.Title
select new UserCollectionView { Cards = c, CardCollections = j };
Session["CardCollection"] = viewModel;
return View(viewModel.ToPagedList(pageNumber, pageSize));
I am trying to use the PagedList to add paging to the results. I have been able to do this when I am not using a query that returns data from 2 databases in a single view. As shown here
My end result looks something like this:
Cards.SeveralColumns CardCollections.ColumnA CardCollections.ColumnB
Row 1 Data from Cards Table A from CardCollections B from CardCollections
Row 2 Data from Cards Table A from CardCollections B from CardCollections
Row 3 Data from Cards Table A from CardCollections B from CardCollections
And so on... I get an error
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
I have tried variations of SQL statements but can't get it to fit with my view model. In SQL Management Studio this brings back the correct results
Select * from Cards Inner Join CardCollections On Cards.CardID = CardCollections.CardID where CardCollections.UserID = 1 and CardCollections.NumberofCopies > 0;
I need a way to pass the query in session so the paging will operate correctly. Any advice is appreciated. :)
Short answer is, you can't. The model needs to be a snapshot of the content and therefore you can't pass an open query across the boundary (either as a hand-off to a session or to the client directly).
What you're seeing is the disposal of the context beyond it's initial use (where you assemble var viewmodel).
With that said, you can cache the results (to save overhead) if querying the data is an expensive operation. Basically, you'd store the entire collection (or at least a large subset of the collection) in the session/memorycache (which can then be manipulated into a paged list). Something to the effect of:
public ActionResult ViewCollection(int? page)
{
var userId = (int) WebSecurity.CurrentUserId;
var pageNumber = page ?? 1;
var pageSize = 5;
ViewBag.OnePageOfCards = pageNumber;
var cacheKey = String.Format("ViewCollection[{0}]", userId);
var entities = GetOrCreateCacheItem<IEnumerable<UserCollectionView>>(cacheKey, () => {
var query = (from c in db.Cards
join j in db.CardCollections on c.CardID equals j.CardID
where (j.NumberofCopies > 0) && (j.UserID == userid)
orderby c.Title
select new UserCollectionView { Cards = c, CardCollections = j }
)
.ToList(); // Force fetch from Db so we can cache
});
return View(entities.ToPagedList(pageNumber, pageSize));
}
// To give an example of a cache provider; Feel free to change this,
// abstract it out, etc.
private T GetOrCreateCacheItem<T>(string cacheKey, Func<T> getItem)
{
T cacheItem = MemoryCache.Default.Get(cacheKey) as T;
if (cacheItem == null)
{
cacheItem = getItem();
var cacheExpiry = DateTime.Now.AddMinutes(5);
MemoryCache.Default.Add(cacheKey, cacheItem, cacheExpiry);
}
return cacheItem;
}
It turns out that I didn't need to pass the query at all. If I let it run through it works fine without the session. I am not really sure why this works but my search query has to be passed. Maybe it is because I am using a viewmodel to perform the query. I will experiment and post if I find anything. Currently the working code is:
public ActionResult ViewCollection(int? page)
{
var userid = (int)WebSecurity.CurrentUserId;
var pageNumber = page ?? 1;
int pageSize = 5;
ViewBag.OnePageOfCards = pageNumber;
ViewBag.Rarity_ID = new SelectList(db.Rarities, "RarityID", "Title");
ViewBag.MainType_ID = new SelectList(db.MainTypes, "MainTypeID", "Title");
ViewBag.CardSet_ID = new SelectList(db.CardSets, "CardSetID", "Title");
ViewBag.SubType_ID = new SelectList(db.SubTypes, "SubTypeID", "Title");
var viewModel = from c in db.Cards
join j in db.CardCollections on c.CardID equals j.CardID
where (j.NumberofCopies > 0) && (j.UserID == userid)
orderby c.Title
select new UserCollectionView { Cards = c, CardCollections = j };
return View(viewModel.ToPagedList(pageNumber, pageSize));

ASP.NET MVC - Save Generated HTML as PDF to folder

I've generated an HTML page in MVC ASP.NET C#. (with html helpers)
I would like to automaticly save this page as a pdf in a specific folder
Currently, when someone submits a form it gets send to a DB, but I also want that [HttpPost] to turn that submitted form to a pdf
Example: http://example1234.com/Persons/details/15
How do i save this as a pdf?
private string datadir = null;
private string wkhtmltopdf = null;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Person person)
{
datadir = ConfigurationManager.AppSettings["datadir"];
wkhtmltopdf = ConfigurationManager.AppSettings["wkhtmltopdf"];
if (ModelState.IsValid)
{
db.People.Add(person);
db.SaveChanges();
//here the PDF should be created
System.IO.File.WriteAllText("details/" + person.ID +".html"));
var pdf1 = new ProcessStartInfo(wkhtmltopdf);
pdf1.CreateNoWindow = true;
pdf1.UseShellExecute = false;
pdf1.WorkingDirectory = datadir + "tmp\\";
pdf1.Arguments = "-q -n --disable-smart-shrinking Pdf." + person.ID + ".html Pdf." + person.ID + ".pdf";
using (var process = Process.Start(pdf1))
{
process.WaitForExit(99999);
Debug.WriteLine(process.ExitCode);
}
return View(person);
}
posted it as an answer to one of my other questons, but it also applies here so here you go for those interested.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Person person)
datadir = ConfigurationManager.AppSettings["datadir"];
//datadirectory defined in Web.config
//also possible to hardcode it here, example: "c:/windows/PDFfolder"
wkhtmltopdf = ConfigurationManager.AppSettings["wkhtmltopdf"];
//directory to the file "wkhtmltopdf", downloaded it somewhere
//just like above, defined at web.config possible to hardcode it in
ViewData["IsModelValid"] = ModelState.IsValid ? "true" : "false";
//valid checker
if (ModelState.IsValid) //check if valid
{
db.People.Add(person); //add to db
db.SaveChanges();
var fileContents1 = System.IO.File.ReadAllText(datadir + "Template.html");
//get template from datadirectory
fileContents1 = fileContents1.Replace("#NAME#", person.Name);
//replace '#NAME#' by the name from the database table person.Name
System.IO.File.WriteAllText(datadir + "tmp\\Template." + person.ID + ".html", fileContents1);
//create a new html page with the replaced text
//name of the file equals the ID of the person
var pdf1 = new ProcessStartInfo(wkhtmltopdf); //start process wkhtmltopdf
pdf1.CreateNoWindow = true; //don't create a window
pdf1.UseShellExecute = false; //don't use a shell
pdf1.WorkingDirectory = datadir + "tmp\\"; //where to create the pdf
pdf1.Arguments = "-q -n --disable-smart-shrinking Overeenkomst." + person.ID + ".html Overeenkomst." + person.ID + ".pdf";
//get the html to convert and make a pdf with the same name in the same directory
}
return View(person);
}

max lengt or else dots - How or what should i write?

I want the script to show max 26 letters and if there is more I want it to make (...) <-- so that you can se there is more letters in the link.
First I put a bit of a script I have for another site containing a variable to do that, however it doesn't work in RSS:
{
temp.Add(titel);
count++;
string titel_kort = titel;
if (titel.Length > 26)
{
titel_kort = titel.Substring(0, 26) + "...";
}
}
And this is the script I want to integrate to:
#using System.Xml.XPath;
#using System.Xml;
#{
try
{
XmlTextReader udBrudRSS = new XmlTextReader("http://tidende.dk/rss.aspx");
XmlDocument doc = new XmlDocument();
doc.Load(udBrudRSS);
XmlNodeList rssItems = doc.SelectNodes("//item");
var count = 0;
foreach (XmlNode node in rssItems )
{
count++;
if (count > 3) { break; }
<div class="nyhedlink">- #node["title"].InnerText</div>
}
}
catch {}
}
You could something like this :
using (var webclient = new WebClient())
{
var data = webclient.DownloadData("http://tidende.dk/rss.aspx");
var oReader = new XmlTextReader(new MemoryStream(data));
var xml = XDocument.Load(oReader);
var values = xml.XPathSelectElements("//item").Take(3).Select(p => new
{
Link = p.XPathSelectElement("//link").Value,
Title = (p.XPathSelectElement("./title").Value.Length > 26) ?
p.XPathSelectElement("./title").Value.Substring(0, 26).Trim() + "..." :
p.XPathSelectElement("./title").Value.Trim()
});
foreach (var item in values)
{
<div class="nyhedlink">- #item.Title</div>
}
}
Sometimes is better use WebClient to make the petition instead of XmlTextReader see this question for a good explanation.

Scroll to alphabet in a List (ArrayCollection dataProvider) (Alphabet Jump)

Hopefully this is easy but that sometimes means its impossible in flex and I have searched quite a bit to no avail.
Say I have a list (LIST#1) of artists:
2Pac
Adele
Amerie
Beyonce
Jason Aldean
Shakira
The Trews
I also have a list (LIST#2) that has the values #,A-Z - how would I create an alphabet jump?
So If a user clicked on "A" in LIST#2 that would automatically scroll to "Adele" at the top of LIST#1 - not filter so he/she could scroll up to view 2Pac or down to view The Tews if they were not in the view yet.
Its a standard Flex Spark List with an ArrayCollection as the dataProvider - the artist field is called: "title" along with a unique id field that is not visible to the user.
Thanks!
Please see comments on marker answer for discussion on Dictionary that may be faster in some cases. See below for code (HAVE NOT CONFIRMED ITS FASTER! PLEASE TEST):
private function alphabet_listChange(evt:IndexChangeEvent) : void {
var letter:String;
letter = evt.currentTarget.selectedItems[0].toString();
trace(currentDictionary[letter]);
ui_lstLibraryList.ensureIndexIsVisible(currentDictionary[letter]);
}
public function createAlphabetJumpDictionary() : Dictionary {
//alphabetArray is a class level array containing, A-Z;
//alphabetDictionary is a class level dictionary that indexes A-z so alphabetDictionary["A"] = 0 and ["X"] = 25
var currentIndexDict:Dictionary = new Dictionary; //Dictionary is like an array - just indexed for quick searches - limited to key & element
var searchArray:Array = new Array;
searchArray = currentArrayCollection.source; //currentArrayCollection is the main array of objects that contains the titles.
var currentIndex:Number; //Current index of interation
var currentAlphabetIndex:Number = 0; //Current index of alphabet
for (currentIndex = 0; currentIndex < searchArray.length; currentIndex++) {
var titleFirstLetter:String = searchArray[currentIndex].title.toString().toUpperCase().charAt(0);
if (titleFirstLetter == alphabetArray[currentAlphabetIndex]) {
currentIndexDict[titleFirstLetter] = currentIndex;
trace(titleFirstLetter + " - " + currentIndex);
currentAlphabetIndex++;
} else if (alphabetDictionary[titleFirstLetter] > alphabetDictionary[alphabetArray[currentAlphabetIndex]]) {
trace(titleFirstLetter + " - " + currentIndex);
currentIndexDict[titleFirstLetter] = currentIndex;
currentAlphabetIndex = Number(alphabetDictionary[titleFirstLetter] + 1);
}
}
return currentIndexDict;
}
private function build_alphabeticalArray() : Array {
var alphabetList:String;
alphabetList = "A.B.C.D.E.F.G.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z";
alphabetArray = new Array;
alphabetArray = alphabetList.split(".");
return alphabetArray;
}
private function build_alphabetDictionary() : Dictionary {
var tmpAlphabetDictionary:Dictionary = new Dictionary;
for (var i:int=0; i < alphabetArray.length; i++) {
tmpAlphabetDictionary[alphabetArray[i]] = i;
trace(alphabetArray[i] + " - " + i);
}
return tmpAlphabetDictionary;
}
private function buildCurrentDictionary() : void {
trace("Collection Changed");
currentDictionary = new Dictionary;
currentDictionary = createAlphabetJumpDictionary();
}
The Flex Spark list has a very convenient method called ensureIndexIsVisible(index). Check the Flex reference documentation. All you have to do is to find the index of the first artist for the corresponding selected alphabet letter:
public function findAlphabetJumpIndex():Number
{
var jumpToIndex:Number;
var selectedLetter:String = alphabethList.selectedItem;
for (var i:int=0; i < artists.length; i++)
{
var artistName:String = artists.getItemAt(i);
var artistFirstLetter:String = artistName.toUpperCase().charAt(0);
if (artistFirstLetter == selectedLetter)
{
jumpToIndex = i;
break;
}
}
return jumpToIndex;
}
You can iterate your artist list data provider and check if artist name starts with selected alphabet from list two. When corresponding artist is found, set artist list selected index a value what you get from iterating data.

How to know what class is referenced by a Class object?

We have the Class object (an object that reference a Class) so you can create objects from that Class object:
var classObject:Class = package.to.class.AClass;
var objectFromClass:AClass = new classObject();
Now, I want to know what object is referenced by classObject. For example:
function Creator(classObject:Class):AClass
{
// here I want to know what class is referenced by classObject
return new classObject();
}
var classObject:Class = package.to.class.AClass;
var objectFromClass:AClass = Creator(classObject);
This works, but what if I pass a Class object that do not reference to AClass? I want to know if this happends and make somthing about it.
--- EDIT ---
Searching I found this function
flash.utils.getQualifiedClassName(value:*):String
This function returns the name of the class, for example:
var name:String = '';
// name = ''
name = flash.utils.getQualifiedClassName(package.to.class.AClass);
// name = 'AClass'
name = ''
// name = ''
var anInstance:AClass = new AClass();
name = flash.utils.getQualifiedClassName(anInstance);
// name = 'AClass'
So, all I have to do is to compare the results of that function:
function Creator(classObject:Class):AClass
{
var anInstance:AClass = new AClass();
var className:String = flash.utils.getQualifiedClassName(anInstance);
var classObjectName:String = flash.utils.getQualifiedClassName(classObject);
// here className and classObjectName are 'AClass' :)
if (className != classObjectName)
throw new Error('The classes are different');
return new classObject();
}
var classObject:Class = package.to.class.AClass;
var objectFromClass:AClass = Creator(classObject);
--- EDIT 2 ---
Another method is to use the constructor property of the Object class:
function Creator(classObject:Class):AClass
{
var tempInstance:AClass = new AClass();
var tempClassObject:Class = Object(tempInstance).constructor;
if (classObject != tempClassObject)
throw new Error('The classes are different');
return new classObject();
}
I found that the most simplest (not know if it's the fastest) way to accomplish this task is in the next example:
function Creator(classObject:Class):AClass
{
var anInstance:Object = new classObject() as AClass;
if (anInstance == null)
throw new Error('The classes are different');
return new classObject(); // or return anInstance as AClass;
}
This also works if AClass is an Interface.