asp.net mvc 4. 0 - multiple action to render data to same view - asp.net-mvc-4

How i can overload actions in a controller.
public ActionResult OnlineHome()
{
OnlineDataModel dm = new OnlineDataModel();
dm.CatagoryData = new List<category>();
dm.ProductData = new List<product>();
dm.CatagoryData = db.categories.ToList();
return View(dm);
}
[HttpPost]
public ActionResult OnlineHome(int CategoryId)
{
OnlineDataModel dm = new OnlineDataModel();
dm.CatagoryData = new List<category>();
dm.ProductData = new List<product>();
dm.CatagoryData = db.categories.ToList();
Convert.ToInt32(CategoryId) select p).ToList() ;
var data= db.products.Where(d => d.CategoryID == CategoryId).ToList();
dm.ProductData = data.ToList();
ViewBag.data = data;
return View(dm);
}
[HttpPost]
public ActionResult OnlineHome(OnlineDataModel data)
{
return View();
}
please help. how i can overload the actions which will render data to same view

You can use the ActionName attribute if you want your code to do overloading.
[ActionName("MyOverloadedName")]
To Render the Same View, You can pass the Model and ViewName like this.
return View("ViewName",model);

you can provide ActionName attribute with different name while calling it from View. Like
[ActionName("OnlineHomeWithCategoryId")]
public ActionResult OnlineHome(int CategoryId)
{
}
[ActionName("OnlineHomeWithData")]
public ActionResult OnlineHome(OnlineDataModel data)
{
}
Now you just need to use these action names while calling these action metho

Related

How can I pass values to the URL in ASP.NET Core 6 MVC?

I am trying to pass an Id from one controller to another by passing the value in the url and calling it in the other controller. So far I have tried everything and I can't get it to work. Can anyone help?
Here is the flight controller
[HttpGet]
public IActionResult SearchFlights(string origin, string destination, DateTime departureDate)
{
var flights = _context.Flights
.Where(f => f.DepartureAirport == origin
&& f.ArrivalAirport == destination
&& f.DepartureDatetime.Date == departureDate.Date)
.ToList();
ViewBag.Origin = origin;
ViewBag.Destination = destination;
ViewBag.DepartureDate = departureDate;
return View(flights);
}
[HttpPost]
public IActionResult SearchFlights(int flightId)
{
string url = string.Format("/Reservation/AddPassenger?flightId={0}", flightId);
return Redirect(url);
}
Here is the ReservationController:
[HttpGet]
public IActionResult AddPassenger([FromRoute] int flightId)
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddPassenger(Passenger passanger, [FromRoute] int flightId)
{
Passenger passenger = new Passenger()
{
Name = passanger.Name,
Email = passanger.Email,
PhoneNumber = passanger.PhoneNumber,
PassportNumber = passanger.PassportNumber,
PaymentMethod = passanger.PaymentMethod,
};
_context.Passengers.Add(passenger);
_context.SaveChanges();
int passengerId = passenger.PassengerId;
Reservation reservation = new Reservation()
{
FlightId = flightId,
SeatId = 2,
PassengerId = passengerId,
ReservationStatus= "Confirmed",
ReservationDate= DateTime.Now,
};
_context.Reservations.Add(reservation);
_context.SaveChanges();
return RedirectToAction("Index");
}
Essentially this is a search mechanism to display the data when the user clicks book the ID should be sent to the Url, but it doesn't, the url in the browser is like this
https://localhost:2213/Reservation/AddPassenger?.
Am I doing something wrong?
If you want to pass value from one controller to another controller in .netcore, I have a suggestion like below:
Try to use TempData:
In flight controller:
[HttpPost]
public IActionResult SearchFlights(int flightId)
{
TempData["flightId"] = flightId;
return RedirectToAction("AddPassenger", "Reservation");
}
And in Reservation Controller:
[HttpGet]
public IActionResult AddPassenger()
{
var flightId = TempData["flightId"];
return View();
}
result:
Or
Just Remove the [FromRoute]
[HttpGet]
public IActionResult AddPassenger( int flightId)
{
return View();
}
result:

communication between controllers asp.net mvc by viewdata

i wanna send an object or at least its ID from a controller to another controller so how can i do it ?
how to send a variable from a controller to another in asp.net mvc
does this instruction solve the problem or it's just for the controller -view communication ?
this is the method in the first controller :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult login(Utilisateur u)
{
if (u.login != null && u.Password != null)
{
using (BD_GestionDepences db = new BD_GestionDepences())
{
string x;
string hash = GetSHA1HashData(u.Password);
x = hash;
u.Password = x;
u.ConfirmPassword = x;
Utilisateur utilisateurV = log_existe("admin", u.login, u.Password);
if (utilisateurV != null)
{
return RedirectToAction("admin");
}
else { ViewBag.ResultMessage = "verifier login et password !"; }
}
}
return View(u);
}
and this is my 2nd controller : i wanna send the user login from the login method in the first controller to the create method in this controller :
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using mvc_depences.Models;
namespace mvc_depences.Controllers
{
public class ProjetController : Controller
{
private BD_GestionDepences db = new BD_GestionDepences();
public ActionResult Index()
{
return View();
}
//public ActionResult beforeCreate()
//{
//}
public ActionResult Create()
{
ViewBag.UtilisateurID = new SelectList(db.Utilisateurs, "UtilisateurID");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ProjetId,nomP,DateDebut,DateFinPrevue,DateFinReele,etat,Description,UtilisateurID")]Projet projet)
{
if(ModelState.IsValid)
{
db.Projets.Add(projet);
db.SaveChanges();
return RedirectToAction("Index");
};
return View(projet);
}
public ActionResult Projet_Read([DataSourceRequest]DataSourceRequest request)
{
IQueryable<Projet> projets = db.Projets;
DataSourceResult result = projets.ToDataSourceResult(request, projet => new
{
ProjetId = projet.ProjetId,
nomP = projet.nomP,
DateDebut = projet.DateDebut,
DateFinPrevue = projet.DateFinPrevue,
DateFinReele = projet.DateFinReele,
etat = projet.etat,
});
return Json(result);
}
//public ActionResult Index()
//{
// return View();
//}
}
}
You cannot use ViewData for send a variable from a controller to another controller.
Can be perform with On successful authentication, call the following method
return RedirectToAction("ActionName", "ControllerName", new {variable1 = value1, variable2 = value2/*...etc*/});
hey guys finally my problem is solved :D !!!
i used the TempData it works like ViewData and ViewBag but its for communication between controllers

MVC: How to retain values in Model after an [HttpPost]

The first line of my controller is initalizing my model:
ViewModel myModel = new ViewModel;
public ActionResult MyPage(string id)
{
var concatString = id.Split(',');
myModel.newString1 = concatString [0];
myModel.newString2 = concatString [1];
myModel.newString3 = concatString [2];
return View(meterModel);
}
[HttpPost]
public ActionResult MyPage()
{
ValidateStuff(Request);
return View(myModel)
}
private void ValidateSuff(HttpRequestBase request)
{
//Below is basic summery of regexmatching of form fields
if (request.form[Stuff1] != "")
{
myModel.string4 = request.form[Stuff1];
}
else
{
ModelState.AddModelError("Stuff1", "Required Field.");
}
}
I am passing 50% of the information to that model from another controller (This works fine), and need the other 50% from a form I generated. During the HttpPost however the model re-initializes and I lost the first 50% of my object values...
Am I doing this wrong?

Update div after POST method

I have a page with a form for registering a new user. After pressing the submit button the following action method (which checks if a user is already in DB and inserts a new one if there isn't) executes in my controller.
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
int result = this.isUserInDB(model.Email);
ViewBag.numberOfEmails = result;
if (result == 0)
{
this.insertNewUserInDB(model.Name, model.Surname, model.Password, model.Email);
}
return View();
}
Now I would like to have a div, on the same page as the form, where I would display a notification message if:
a user is already in the db
a user was inserted in the db
I can't accomplish this now, because I always return the same view. I tried changin the return type of the action method to void, but that displays a blank page.
How can I solve this? Thank you in advance.
I can't accomplish this now, because I always return the same view.
That's not a problem. In your view you could have some conditional logic:
if (Model.NewUserInserted)
{
<div>A new user was created</div>
}
else if (Model.UserAlreadyExists)
{
<div>The specified user already exists</div>
}
of course you should now write your view model:
public class MyViewModel
{
public int NumberOfEmails { get; set; }
public bool NewUserInserted { get; set; }
public bool UserAlreadyExists { get; set; }
}
the controller action that is initially rendering this view should pass an empty model:
return View(new MyViewModel());
and your POST action should set the corresponding properties:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
int result = this.isUserInDB(model.Email);
var viewModel = new MyViewModel();
viewModel.NumberOfEmails = result;
if (result == 0)
{
this.insertNewUserInDB(model.Name, model.Surname, model.Password, model.Email);
viewModel.NewUserInserted = true;
}
else
{
viewModel.UserAlreadyExists = true;
}
return View(viewModel);
}
and of course your view should be strongly typed to the view model:
#model MyViewModel
and you should get rid of all ViewBag.

How to get Kendo Dropdown selected should fill Kendo grid

I tried this but from my controller data is returning but not binding to kendo grid
This is my controller
public ActionResult Index(string LocationId)
{
using (var client = new HttpClient())
{
IList<AssetsByLocation> _assetCompanyDetailslist;
AssetRepository assetrep = new AssetRepository();
Guid LocationID = new Guid();
if (Request.Params["LocationId"] != null)
{
LocationID = new Guid(Request.Params["LocationId"].ToString());
_assetCompanyDetailslist = assetrep.GetAssetsForLocation(LocationID);
var model = _assetCompanyDetailslist;
return View(model);
}
else
{
return View();
}
}
}
in my .cshtml kendo grid i used this to read
.Read(read => read.Action("Index", "AssetByLocation").Data("getMsgType"))
This is my event in dropdownlist
.Events(events => events.Change("OnMsgTypeChange"))
There are my functions
var ddlItem;
function getMsgType() {
return {
LocationId: ddlItem
}
}
function OnMsgTypeChange(e) {
ddlItem = this.value();
$("#Grid").data("kendoGrid").dataSource.read();
}
I Finally got with this,
public ActionResult Index([DataSourceRequest]DataSourceRequest request, string LocationId)
{
if (Request.Params["LocationId"] != null)
{
using (var client = new HttpClient())
{
AssetRepository assetrep = new AssetRepository();
Guid LocationID = new Guid();
LocationID = new Guid(Request.Params["LocationId"].ToString());
var msgs = assetrep.GetAssetsForLocation(LocationID).ToDataSourceResult(request);
return Json(msgs);
}
}
else
{
return View();
}
}