Viewbag id returns no data - c#

This is the start of my index.cshtml:
#model IEnumerable<UsageReportViewModel>
#{
ViewBag.Title = "UsageReport";
}
<h2>UsageItem</h2>
#(Html.Kendo().Grid(Model)
.Name("Index")
.DataSource(data => data
.Ajax()
.Read(read => read.Action("GetUsageItems", "UsageReport", new { id = ViewBag.usageReportId }))
.Model(model => model.Id(m => m.Id))
^ Index:
public ActionResult Index(int id)
{
return View();
}
public ActionResult Details(int id)
{
ViewBag.usageReportId = id;
return View();
}
public ActionResult Get([DataSourceRequest] DataSourceRequest request)
{
var GetFile = UsageReportSelection();
return Json(GetFile.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public ActionResult GetUsageItems([DataSourceRequest] DataSourceRequest request)
{
int id = ViewBag.usageReportId; // <--
var GetFile = UsageReportItems(id);
return Json(GetFile.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
The int id from method GetUsageItems is returning "0". I need this to pass through some data like the public ActionResult index is doing with the Get method. I know I am doing something wrong just not sure what.

You don't get the value of ViewBag.usageReportId the way you are trying to get it. The ViewBag value you are passing read => read.Action method would come as extra parameter to the Action method at the server side.
So you have two ways to access this values at the controller action method.
One - Change controller action method to have extra parameter as following.
public ActionResult GetUsageItems([DataSourceRequest] DataSourceRequest request, int id)
{
var GetFile = UsageReportItems(id);
return Json(GetFile.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
Follow https://www.telerik.com/forums/pass-additional-parameters-to-read-ajax-datasource-method---mvc to understand the example.
Two - Access the id from QueryString parameters.
public ActionResult GetUsageItems([DataSourceRequest] DataSourceRequest request)
{
var id = Convert.ToInt32(Request.QueryStrings["id"]);
var GetFile = UsageReportItems(id);
return Json(GetFile.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
This should help you resolve your issue.

Related

How can I send id to controller action method in ASP.NET MVC?

I am working a project and I had some trouble. I want to send id from html beginform but I couldn't do it.
I want to send /BuyTourTicket/tourid
This is my code:
public ActionResult TourTicket(int id)
{
var tour = db.TBLTUR.Find(id);
ViewBag.tourid = tour.id;
ViewBag.tourname = tour.tur_basligi.ToString();
ViewBag.kalkisYeri = tour.kalkis_yeri.ToString();
ViewBag.tarih = tour.tarih.ToString();
ViewBag.detaylar = tour.detay.ToString();
ViewBag.turYetkilisi = db.TBLTURYETKILISI.Find(id).ad + " " + db.TBLTURYETKILISI.Find(id).soyad;
return View("TourTicket",tour);
}
public ActionResult BuyTourTicket()
{
return View();
}
[HttpPost]
public ActionResult BuyTourTicket(int id)
{
TBLTURREZERVASYON reservation = new TBLTURREZERVASYON();
reservation.tur = id;
db.TBLTURREZERVASYON.Add(reservation);
db.SaveChanges();
return View();
}
This is the error I get:
The first, the default route usually describes the id parameter as optional. Therefore change the action method declaration to public ActionResult BuyTourTicket(int? id):
[HttpPost]
public ActionResult BuyTourTicket(int? id)
{
TBLTURREZERVASYON reservation = new TBLTURREZERVASYON();
reservation.tur = id;
db.TBLTURREZERVASYON.Add(reservation);
db.SaveChanges();
return View();
}
The second, change the parameters order in the Html.BeginForm() of the TourTicket.cshtml to:
#using (Html.BeginForm("BuyTourTicket", "Tur", new { id = ViewBag.tourid }, FormMethod.Post))
The route values are third parameter and the HTTP method is the fourth parameter.
I would fix an action route
[HttpPost("{id"})]
public ActionResult BuyTourTicket(int id)
and add Get to another action
[HttGet]
public ActionResult BuyTourTicket()
{
return View();
}

Pass in data parameters to new MVC ActionResult call without showing in URL

I am working with adding a new MVC page and have the method and calls up and running. My issue is that I am not wanting to pass in URL parameters to show in my page but need to pass in the parameters for the method when I do a redirect to my new page. Currently I have it set up like this:
Page.cs
void ToNewPage()
{
Response.RedirectToRoute(new { controller = "ControllerName", action = "ActionName", ID1 = 1, ID2 = 2 });
}
ControllerName.cs
public ActionResult ActionName(int ID1, int ID2)
{
...
return View(model);
}
Currently with my code I get the URL ~/ControllerName/ActionName?ID1=1&ID2=2. I am just wanting the URL to just be ~/ControllerName/ActionName. I know this would be easier on a frontend or maybe through javascript but needing to do this from the ToNewPage method if possible.
There are working codes:
PageController.cs
public class PageController : Controller
{
// GET: Page
public ActionResult Index()
{
return View();
}
public ActionResult ToNewPage()
{
var ids = Newtonsoft.Json.JsonConvert.SerializeObject(new { ID1 = 1, ID2= 2 });
TempData["ids"] = ids;
return RedirectToAction("Index", "NewPage");
}
}
NewPageController.cs
public class NewPageController : Controller
{
// GET: NewPage
public ActionResult Index()
{
if (TempData["ids"] != null)
{
dynamic ids = JsonConvert.DeserializeObject(TempData["ids"] as string);
ViewBag.ID1 = ids.ID1;
ViewBag.ID2 = ids.ID2;
}
return View();
}
}
NewPage\Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>NewPage</h2>
<ul>
<li>ID1: #ViewBag.ID1</li>
<li>ID2: #ViewBag.ID2</li>
</ul>
You should use TempData:
void ToNewPage()
{
TempData["ID1"]="ID1 Value"
TempData["ID2"]="ID2 Value"
Response.RedirectToRoute(new { controller = "ControllerName", action = "ActionName"
});
}
public ActionResult ActionName()
{
int ID1=int.parse(TempData["ID1"].ToString());
int ID2=int.parse(TempData["ID2"].ToString());
return View();
}
You can fill many TempDatas in many controllers and use them in many Views and controllers

How to pass a variable from one ActionResult to another ActionResult? (ASP.NET MVC)

I want to be able to use the value of a string variable passed to one ActionResult, within another ActionResult.. How could i go about doing this?
public ActionResult PassCategoryPlaceHolder(string placeHolder)
{
var result = placeHolder;
return RedirectToAction("EditCategory", result);
}
I want to be able to use 'result' in my other ActionResult as follows:
public ActionResult EditCategory()
{
ViewBag.Message = Convert.ToString(result);
return View();
}
Note: I am trying to avoid sending 'placeHolder' directly to the ActionResult where i need it.
You can do something like this
public ActionResult PassCategoryPlaceHolder(string placeHolder)
{
var result = placeHolder;
return RedirectToAction("EditCategory", new { message = result});
}
And in other method:-
public ActionResult EditCategory(string message)
{
var model = new EditCategoryViewModel();
model.Message = message;
return View(model);
}
Simply use a Session variable:
public ActionResult PassCategoryPlaceHolder(string placeHolder)
{
Session["result"] = placeHolder;
return RedirectToAction("EditCategory");
}
public ActionResult EditCategory()
{
var Message = Convert.ToString(Session["result"]);
return View();
}

About the jump of action in asp.net mvc

Now I have an action A and an action B,I want to jump to action B in action A.But action B has
a parameter "MyModel".If I write like this:
public ActionResult A(MyModel model)
{
...
return B(model);
}
public ActionResult B(MyModel model)
{
...
return View();
}
It will cause an error.
What should I do to transfer the parameter "MyModel" to action B in action A?
Do this:
public ActionResult A(MyModel model)
{
return RedirectToAction("B", model);
}
Try this
public ActionResult A(MyModel model)
{
...
TempData["object"] = new { Model= model };
return RedirectToAction("B");
}
Then in your B action
public ActionResult B(MyModel model)
{
...
var yourObj = TempData["object"];
model=yourObj .Model;
return View();
}

mvc3 RedirectToAction

Why isn't this working. It keeps telling me edit needs a EditStudyModel when I redirect in my Create method. A Redirect should do a get, right?
public ViewResult Create()
{
var createStudyModel = new CreateStudyModel();
return View(createStudyModel);
}
[HttpPost]
public ActionResult Create(CreateStudyModel createStudyModel)
{
try
{
//TODO: Send CreateStudyCommand
return RedirectToAction("Edit", new { scientificStudyId = new Guid("{1C965285-788A-4B67-9894-3D0D46949F11}") });
}
catch
{
return View(createStudyModel);
}
}
[GET("ScientificStudy/Create/{scientificStudyId}")]
public ActionResult Edit(Guid scientificStudyId)
{
//TODO: Query real model
var model = new EditStudyModel() {StudyNr = "T01", StudyName = "Test"};
return View(model);
}
[HttpPost]
public ActionResult Edit(EditStudyModel editStudyModel)
{
try
{
//TODO: Send UpdateStudyCommand
return RedirectToAction(""); //TODO: Terug naar Studie lijst
}
catch
{
return View(editStudyModel);
}
}
You're returning a redirect with a URL as a string, the controller isn't able to parse the GUID and convert it back to a guid object, so it's not able to resolve the correct method signature to use. Change it to:
return RedirectToAction("Edit", new { scientificStudyId = "{1C965285-788A-4B67-9894-3D0D46949F11}" });
and
public ActionResult Edit(string scientificStudyId)
I found the issue. I copy paste my create.cshtml to edit.cshtml Forgot to change the first line:
#model Website.Models.CreateStudyModel --> to --> #model Website.Models.EditStudyModel

Categories