I want to use one action into another action for getting some values as:
[HttpPost]
public ActionResult Playlist(PageInfo p, long ID)
{
//long playid=Convert.ToInt64(p.Where);
var q = from client in my.Clients(0, 0)
join pl in db.Playlists on client.ClientId equals pl.ClientId
select new SimpleViewModel
{
Sequence=pl.PlaylistContentSequenceId,
PlaylistID = pl.PlaylistId,
PlaylistContentID=pl.ContentId
};
return Json(q.ToPage(p, "Sequence"), JsonRequestBehavior.DenyGet);
}
[HttpPost]
public ActionResult Save(List<ItemEditViewModel> data,long playlistid, List<long> deleted,string Title)
{
var playlist = db.Playlists.Include("PlaylistContents").FirstOrDefault(x => x.PlaylistId == playlistid);
for (int i = 0; i < playlist.PlaylistContents.Count; i++)
{
if(deleted.IndexOf(playlist.PlaylistContents[i].PlaylistContentId)>-1){
playlist.PlaylistContents.Remove(playlist.PlaylistContents[i]);
}
}
db.SaveChanges();
long ID=playlistid;
return Playlist(new PageInfo(),ID);
}
as you have seen in the code that after saving the contents into the database, the Playlist controller should be used for returning the Json data.
instead of
return Playlist(new PageInfo(),ID);
try
return RedirectToAction("Playlist", new {p = new PageInfo(), ID = ID});
Related
How can I pass the input type text value to TempData
<input type='text' name='APP_COMMENT' />
#{TempData["APP"] = //This's where I want the input value;}
EDIT:
This's the action that I need to send from the View to Controller (Not Controller to view)
public ActionResult Approved()
{
Entities1 db = new Entities1();
string y=(TempData["APP"]).ToString(); //TempData is send from the View to Controller
decimal sl = (decimal)TempData["rt"];
var sp = db.TB_RST_SVCHDR.Where(x => x.REQ_NO == sl);
foreach (var p in sp)
{
if (p.STATUS == "N")
{
p.STATUS = "A1";
p.APP1_COMMENT = y; //Here's where the TempData is saved
p.APP1_DATEACTION = DateTime.Now;
p.APPROVER1 = "";
var s = p.APPROVER2;
//var ss = p.APPROVER2;
var s2 = p.REQUESTOR_EMPNAME;
TempData["email-act2"] = s2;
//SendEmail(s, ss);
SendEmail(s);
db.SaveChanges();
return View("~/Views/Home/Index.cshtml");
}
}
//return View();
return View("~/Views/Home/Index.cshtml");
}
However your question seems to look more of a Post action. In which case you should consider reading up on how to post data using a form. Use this.
#using (Html.BeginForm("Approved", "Controllername", FormMethod.Post))
{
<input type="text" name="data">
<input type="submit">
}
And set up the controller action like so:
[HttpPost]
public ActionResult Approved(string data)
{
Entities1 db = new Entities1();
string y= data;
decimal sl = (decimal)TempData["rt"];
var sp = db.TB_RST_SVCHDR.Where(x => x.REQ_NO == sl);
foreach (var p in sp)
{
if (p.STATUS == "N")
{
p.STATUS = "A1";
p.APP1_COMMENT = y; //Here's where the TempData is saved
p.APP1_DATEACTION = DateTime.Now;
p.APPROVER1 = "";
var s = p.APPROVER2;
//var ss = p.APPROVER2;
var s2 = p.REQUESTOR_EMPNAME;
TempData["email-act2"] = s2;
//SendEmail(s, ss);
SendEmail(s);
db.SaveChanges();
return View("~/Views/Home/Index.cshtml");
}
}
//return View();
return View("~/Views/Home/Index.cshtml");
}
Unless, you want something dynamic that updates TempData["APP"] when the input changes, what you can do is to assign the value when that form is posted. So, you do something of this nature.
public async Task<IActionResult> OnPostAsync(Model model)
{
model.YourField = TempData["APP"]
}
How to pass below action to another action in order to export it in excel sheet
,I need to pass VL list to another action
public ActionResult Details(int S)
{
SLMEntitiesDB dbContext = new SLMEntitiesDB();
var VL = (from U in dbContext.Users
join P in dbContext.Products
on U.PID equals P.PID
where P.PID == U.PID
select new UP()
{
UserO = U,
ProductO = P
}).Where(U => U.UserO.LID == S).ToList();
TempData["Exc"] = VL;
return View(VL);
}
and the other action within the same controller, but it's not working
public void ExportToExcel()
{
var V = TempData["Exc"] as List;
ExcelPackage pck = new ExcelPackage();
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Report");
ws.Cells["A1"].Value = "UserName";
int rowStart = 1;
foreach (var item in V)// here is the error
{
ws.Cells[string.Format("A{0}", rowStart)].Value = item.UserO.CN;
you'll create another Function\Action on your controller and pass the data from your view to it. Depending on the size of the data, you could do that as a QueryString (note: type .ToString() considerations, html encoding in that approach), but it's more likely you'll store the instance server-side, using TempData[key] or something similar.
The other aspect of what you're attempting to do (export an Excel File) will be handled by the added Action; However, instead of you handling the entire Response writing in the scope of your action, I recommend you define a type that inherits the FileResult type - where you handle HttpResponseBase in the overloaded WriteFile function (example below).
XLSFileResult
This sample type will actually be writing Comma Separate Value (CSV) content, but the Content-Type (coupled with Content-Disposition) will 'indicate' to the client that it is an excel file - the Response will respond with an ".xls" file.
Note: the filename and extension in this sample are actually defined at it's initialization - in the action of the controller.
public class XLSFileResult : FileResult
{
public XLSFileResult() : base(#"application/vnd.ms-excel")
{
Data = new List<UP>();
}
public IEnumerable<UP> Data { get; set; }
protected override void WriteFile(HttpResponseBase response)
{
// note: you'll want to handle this better; I'm just choosing a property of each complex type.
string[] lines = Data.Select(d => string.Join(", ", d.UserO.UserName , d.ProductO.PName)).ToArray();
byte[] buffer = response.ContentEncoding.GetBytes(string.Join(Environment.NewLine, lines));
response.BinaryWrite(buffer);
}
}
Sample Action\Function on the Controller
public ActionResult Details(int S)
{
SLMEntitiesDB dbContext = new SLMEntitiesDB();
var VL = (from U in dbContext.Users
join P in dbContext.Products
on U.PID equals P.PID
where P.PID == U.PID
select new UP()
{
UserO = U,
ProductO = P
}).Where(U => U.UserO.LID == S).ToList();
return View(VL);
}
protected FileResult HandleDataToFileResult(IEnumerable<UP> data)
{
return new XLSFileResult()
{
Data = data,
FileDownloadName = "MyFile.xls" //by virtue of this assignment, a 'Content-Disposition' Response.Header is added to HttpResponseBase
};
}
public FileResult GenerateFile()
{
var data = (IEnumerable<UP>)TempData["GenerateFile"];
return HandleDataToFileResult(data);
}
Razor Page
In this sample of the razor page, we'll use a ActionLink...
#using SLMDemo0.Models
#model IEnumerable<UP>
#{
ViewBag.Title = "Details";
//Review TempData, it's session data that clears at the end of the next request
TempData["GenerateFile"] = Model.ToArray();
}
...
#Html.ActionLink("GenerateFile", "GenerateFile");
I have a ASP .Net Core MVC app where I have a table in a view that is being populated by data from an entity framework query. Following this guide, I've implemented code to paginate the table. For some reason, when the request for the table data is sent from the client side to controller action, there is the following error:
InvalidOperationException: The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IEntityQueryProvider can be used for Entity Framework asynchronous operations.
Here is the controller action:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GetResultList(ResortDataJoinObj resDeals, int page =1)
{
if (ModelState.IsValid)
{
var resultsObj = (from rd in _db.ResortData
join ra in _db.ResortAvailability on rd.RecNo equals ra.RecNoDate
where ra.TotalPrice < Int32.Parse(resDeals.priceHighEnd) && ra.TotalPrice > Int32.Parse(resDeals.priceLowEnd)
select new
{
Name = rd.Name,
ImageUrl = rd.ImageUrl,
ResortDetails = rd.ResortDetails,
CheckIn = ra.CheckIn,
Address = rd.Address,
TotalPrice = ra.TotalPrice
});
int i = 0;
List<ResortDealResultsObject> resultList = new List<ResortDealResultsObject>();
foreach (var row in resultsObj)
{
var tempVm = new ResortDealResultsObject
{
Name = row.Name,
ImageUrl = row.ImageUrl,
ResortDetails = row.ResortDetails,
CheckIn = row.CheckIn,
Address = row.Address,
TotalPrice = row.TotalPrice
};
resultList.Add(tempVm);
}
int pageSize = 3;
var model = await PaginatedList<ResortDealResultsObject>.CreateAsync(resultList.AsQueryable(), page, pageSize);
ResortDataJoinObj joinObj = new ResortDataJoinObj();
joinObj.PageList = model;
ViewBag.rowsReturned = true;
return View(joinObj);
}
return View(resDeals);
}
It looks like the error is being caused by the line var model = await PaginatedList<ResortDealResultsObject>.CreateAsync(resultList.AsQueryable(), page, pageSize);
This line is calling a method within the class PaginatedList, which is implemented in its own file (as outlined in the guide):
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
There are no pre-compiler or compilation errors so I'm not sure exactly what is wrong here since I'm following the guide pretty closely. What could be causing the error?
List<ResortDealResultsObject> resultList = new List<ResortDealResultsObject>();
foreach (var row in resultsObj)
{
var tempVm = new ResortDealResultsObject
{
Name = row.Name,
ImageUrl = row.ImageUrl,
ResortDetails = row.ResortDetails,
CheckIn = row.CheckIn,
Address = row.Address,
TotalPrice = row.TotalPrice
};
resultList.Add(tempVm);
}
This code is not generated by entity framework and does not provide asynchronious calls.
You already have a List when you call the ToListAsync() method so there is no point to cast it to a Queryable and call ToListAsync() on it
The following code should do the work
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GetResultList(ResortDataJoinObj resDeals, int page =1)
{
if (ModelState.IsValid)
{
var resultsObj = from rd in _db.ResortData
join ra in _db.ResortAvailability on rd.RecNo equals ra.RecNoDate
where ra.TotalPrice < Int32.Parse(resDeals.priceHighEnd) && ra.TotalPrice > Int32.Parse(resDeals.priceLowEnd)
select new ResortDealResultsObject
{
Name = rd.Name,
ImageUrl = rd.ImageUrl,
ResortDetails = rd.ResortDetails,
CheckIn = rd.CheckIn,
Address = rd.Address,
TotalPrice = rd.TotalPrice
};
int pageSize = 3;
var model = await PaginatedList<ResortDealResultsObject>.CreateAsync(resultsObj, page, pageSize);
ResortDataJoinObj joinObj = new ResortDataJoinObj();
joinObj.PageList = model;
ViewBag.rowsReturned = true;
return View(joinObj);
}
return View(resDeals);
}
I didn't test it so there could be some compile time errors but the logic is there :)
Can anyone help me correct the issue im having creating a view in MVC. Normally i just use Add/View and it scaffolds a view for me based upon my created method. The only problem is that this time i am creating a method to pass to view and i keep getting this error message
The model item passed into the dictionary is of type 'UserJob',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[UserJob]'.
The Methods i have written are the following...
public ActionResult AddJob(string userCode)
{
var jobs = jobsClient.GetAlljobs();
var alljobsCode = (from s in jobs select s.jobCode).ToList();
var usersJobs = (from s in db.UserJobs
where s.userCode == userCode
select s.jobCode).ToList();
var jobsNeeded = alljobsCode.Except(usersJobs);
List<UserJobsDTO> list = listBuilder(jobs, jobsNeeded);
ViewBag.jobCode = new SelectList(list, "jobCode", "jobDescription");
var model = new UserJob { userCode = userCode };
return View("AddJob", model);
}
private List<UserJobsDTO> listBuilder(
jobsService.jobsDTO[] jobs, IEnumerable<string> jobsNeeded)
{
List<UserJobsDTO> d = new List<UserJobsDTO>();
var f = jobsNeeded.ToArray();
var a = jobs.ToArray();
for (int i = 0; i < f.Length; i++)
{
d.Add(new UserJobsDTO()
{
jobCode = f.ElementAt(i),
description = a[i].jobDescription
});
}
return d;
}
When im debugging all of the required data is being passed to all the correct variable i am declaring, but the view just isnt playing ball. I was under the impression that scaffolding would automatically generate a useable View for me in Razor?? But this method just want play. Can anyone point me in the right direction??
Corrected version
public ActionResult AddJob(string userCode)
{
var jobs = jobsClient.GetAlljobs();
var alljobsCode = (from s in jobs select s.jobCode).ToList();
var usersJobs = (from s in db.UserJobs
where s.userCode == userCode
select s.jobCode).ToList();
var jobsNeeded = alljobsCode.Except(usersJobs);
List<UserJobsDTO> list = listBuilder(jobs, jobsNeeded);
ViewBag.jobCode = new SelectList(list, "jobCode", "jobDescription");
// var model = new UserJob { userCode = userCode };
return View("AddJob", usersJobs );
}
you will need to pass ienumarable here not an object type.
Update
#model IEnumerable<UserJobs>
foreach(var item in Model){
<span>#item.JobId</span>
<span>#item.JobName</span>
}
I have created an action result that allows restuarant to save their menu to a database. My issue is that I need to use the menuID for another controller but when I run the code the the variable menuID is always 0 instead of the value that was just added to the database.
Any help would be grateful.
Create Menu Action Result
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MenuViewModel model)
{
if (ModelState.IsValid)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
using (var objCtx = new ApplicationDbContext())
{
var currentrestaurant = (from r in objCtx.Restaurants
where r.UserID == currentUser.Id
select r).First<Restaurant>().id;
var menu = new Menu() { Name = model.Name, Restaurantid = currentrestaurant };
var menuID = menu.Id;
db.Menus.Add(menu);
db.SaveChanges();
return RedirectToAction("Create", "Meal", new { MenudID = menuID});
}
}
return View();
}
Most likely the ID is generated in database. If this is the case menu.Id will have the actual value after you save the object to DB, not before. So you need to reorder your code:
var menu = new Menu() { Name = model.Name, Restaurantid = currentrestaurant };
db.Menus.Add(menu);
db.SaveChanges();
return RedirectToAction("Create", "Meal", new { MenudID = menu.Id});
Side note. Make sure parameter in the last line is spelled correctly - shouldn't it be MenuID instead of MenudID?