My server/client side application has following controllers. However when I post/create a reservation, it does not the hold/cache the value of (id) property return (CreatedAtAction(nameof(GetById), new{id=order.id}, order} method, when post action goes out of scope. Therefore GetById(int id) does not receive last id generated rather shows 0. However data commits successfully in the database with valid id.
Server side controller:
[HttpGet("{id:int}")]
public ActionResult<OrderTable> GetById(int id)
{
var order = _context.ReservationsTables.FirstOrDefault(o => o.Id == id);
if(order == null)
{
return NotFound();
}
else
{
return order;
}
}
[HttpPost]
public ActionResult<OrderTable> CreateOrder(OrderTable order)
{
_context.ReservationsTables.Add(order);
_context.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = order.Id }, order);
}
Client Side controller:
public async Task<IActionResult> CreatePostAsync(OrderTable order)
{
var httpClient = _clientFactory.CreateClient();
HttpResponseMessage response = await httpClient.PostAsJsonAsync("https://localhost:44387/api/Reservation", order);
if (response.IsSuccessStatusCode)
{
var orderResult = await response.Content.ReadAsAsync<OrderTable>();
return RedirectToAction("ThankYouAsync", new { id = order.Id });
}
else
{
return View("An error has occurred");
}
}
public async Task<IActionResult> ThankYouAsync(int orderId)
{
var httpClient = _clientFactory.CreateClient();
httpClient.BaseAddress = new Uri("https://localhost:44387/");
HttpResponseMessage response = await httpClient.GetAsync("api/Reservation/" + orderId);
if (response.IsSuccessStatusCode)
{
var orderResult = await response.Content.ReadAsAsync<OrderTable>();
return View(orderResult);
}
else
{
return View("An error has occurred");
}
}
[HttpGet]
public async Task<IActionResult> Create()
{
await PopulateRestaurantDropDownListAsync();
return View();
}
The redirected action has the following signature
Task<IActionResult> ThankYouAsync(int orderId)
Note that the parameter name is orderId.
Yet when the redirection is done,
return RedirectToAction("ThankYouAsync", new { id = order.Id });
the value object is defined new { id = order.Id }
The parameter names need to match for it to work as expected.
So update RedirectToAction to use the correct property name
return RedirectToAction("ThankYouAsync", new { orderId = order.Id });
Note the new { orderId = order.Id } in the value object with matching orderId parameter.
Related
I am in "User Add" page. I have an Id which coming from "Visa Type" page.
When my page cannot be pair with model state, the Id doesn't exist in the URL. I need this Id. How can I return again?
Controller
[HttpGet]
public IActionResult AddUser(int visaTypeId)
{
ViewBag.Id = visaTypeId;
Guid g = Guid.NewGuid();
ViewBag.UniqueUser = g;
return View();
}
[HttpPost]
public async Task<IActionResult> AddUser(UserModel userModel, string uniqueUser, int visaTypeId)
{
if (ModelState.IsValid)
{
var result = await _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
var response = await result.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);
if (responseModel.Success == false)
{
//ViewBag.Message = responseModel.Message;
ModelState.AddModelError("", responseModel.Message);
}
if (result.IsSuccessStatusCode)
{
return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
}
}
return View();
}
You can pass back whatever you obtain from your view.
[HttpPost]
public async Task<IActionResult> AddUser(UserModel userModel, string uniqueUser, int visaTypeId)
{
if (ModelState.IsValid)
{
var result = await _client.PostAsJsonAsync<UserModel>("users/adduser", userModel);
var response = await result.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<ResponseModel>(response);
if (responseModel.Success == false)
{
//ViewBag.Message = responseModel.Message;
ModelState.AddModelError("", responseModel.Message);
}
if (result.IsSuccessStatusCode)
{
return RedirectToAction("AddApplicant", "Applicant", new { uniqueUser = uniqueUser });
}
}
ViewBag.VisaTypeId = VisaTypeId;
ViewBag.uniqueUser = uniqueUser;
return View(userModel);
}
enter image description here
First step...Opened WCF created IService:
namespace CRUDOperationWCFMVC
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
bool CreateDetails(EmployeeDetails employeeDetails);
[OperationContract]
bool UpdateDetails(EmployeeDetails employeeDetails);
[OperationContract]
bool DeleteDetails(int id);
[OperationContract]
List<EmployeeDetails> GetDetails();
}
public class EmployeeDetails
{
[DataMember]
public int EmpID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Location { get; set; }
[DataMember]
public int? Salary { get; set; }
}
}
Step 2: then I implemented service code:
public class Service1 : IService1
{
DataClasses1DataContext dcd = new DataClasses1DataContext();
public bool CreateDetails(EmployeeDetails employeeDetails)
{
Nevint emp = new Nevint();
emp.EmpID= employeeDetails.EmpID;
emp.Name = employeeDetails.Name;
emp.Location = employeeDetails.Location;
emp.Salary = employeeDetails.Salary;
dcd.Nevints.InsertOnSubmit(emp);
dcd.SubmitChanges();
return true;
}
public bool DeleteDetails(int id)
{
var delete = (from v in dcd.Nevints where v.EmpID==id select v).FirstOrDefault();
dcd.Nevints.DeleteOnSubmit(delete);
dcd.SubmitChanges();
return true;
}
public List<EmployeeDetails> GetDetails()
{
List<EmployeeDetails> details = new List<EmployeeDetails>();
var select= (from v in dcd.Nevints select v);
foreach (var i in select)
{
EmployeeDetails emp = new EmployeeDetails();
emp.EmpID = i.EmpID;
emp.Name = i.Name;
emp.Location = i.Location;
emp.Salary = i.Salary;
details.Add(emp);
}
return details;
}
public bool UpdateDetails(EmployeeDetails employeeDetails)
{
var update = (from v in dcd.Nevints.ToList() where employeeDetails.EmpID==v.EmpID select v).FirstOrDefault();
update.EmpID = employeeDetails.EmpID;
update.Name = employeeDetails.Name;
update.Location = employeeDetails.Location;
update.Salary = employeeDetails.Salary;
dcd.SubmitChanges();
return true;
}
}
Step 3: then I add linq to sql, opened my ASP.NET MVC project for consuming, and added a controller and wrote this code:
namespace ConsumingClient.Controllers
{
public class EmpdetailsController : Controller
{
ServiceReference1.Service1Client serobj=new ServiceReference1.Service1Client();
ServiceReference1.EmployeeDetails empdetails=new ServiceReference1.EmployeeDetails();
// GET: Empdetails
public ActionResult Index()
{
List<employee> lstemp = new List<employee>();
var result = serobj.GetDetails();
foreach (var i in result)
{
employee emp = new employee();
empdetails.EmpID = i.EmpID;
empdetails.Name = i.Name;
empdetails.Location = i.Location;
empdetails.Salary = i.Salary;
lstemp.Add(emp);
}
return View(result);
}
// GET: Empdetails/Details/5
public ActionResult Details(int id)
{
Employees emp = new Employees();
return View();
}
// GET: Empdetails/Create
public ActionResult Create()
{
return View();
}
// POST: Empdetails/Create
[HttpPost]
public ActionResult Create(Employees employees)
{
try
{
// TODO: Add insert logic here
empdetails.EmpID=employees.EmpID;
empdetails.Name = employees.Name;
empdetails.Location = employees.Location;
empdetails.Salary = employees.Salary;
serobj.CreateDetails(empdetails);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Empdetails/Edit/5
public ActionResult Edit(int id)
{
Employees emp = new Employees();
var result = serobj.GetDetails().FirstOrDefault(a=>a.EmpID==id);
emp.EmpID = result.EmpID;
emp.Name = result.Name;
emp.Location = result.Location;
emp.Salary = result.Salary;
return View(emp);
}
// POST: Empdetails/Edit/5
[HttpPost]
public ActionResult Edit(Employees employees)
{
try
{
// TODO: Add update logic here
empdetails.EmpID = employees.EmpID;
empdetails.Name = employees.Name;
empdetails.Location = employees.Location;
empdetails.Salary = employees.Salary;
serobj.UpdateDetails(empdetails);
return RedirectToAction("Index");
}
catch
{
return View(employees);
}
}
// GET: Empdetails/Delete/5
public ActionResult Delete(int id)
{
Employees emp = new Employees();
var result = serobj.GetDetails().FirstOrDefault(a=>a.EmpID==id);
emp.EmpID = result.EmpID;
emp.Name = result.Name;
emp.Location = result.Location;
emp.Salary = result.Salary;
return View(emp);
}
// POST: Empdetails/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
serobj.DeleteDetails(id);
return RedirectToAction("Index");
}
catch
{
return View(id);
}
}
}
}
Data was displaying fine. I can create data.
However, when I click on edit and delete, I'm getting an error:
ERROR Message "Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'ConsumingClient.Controllers.EmpdetailsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
This error is thrown if you attempt to call this controller action and you do not specify the id either in the path portion or as query string parameter. Since your controller action takes an id as parameter you should make sure that you always specify this parameter.
Make sure that when you are requesting this action you have specified a valid id in the url:
http://example.com/somecontroller/Edit/123
If you are generating an anchor, make sure there's an id:
#Html.ActionLink("Edit", "somecontroller", new { id = "123" })
If you are sending an AJAX request, also make sure that the id is present in the url.
If on the other hand the parameter is optional, you could make it a nullable integer:
public ActionResult Edit(int? id)
but in this case you will have to handle the case where the parameter value is not specified.
https://coderedirect.com/questions/197477/mvc-the-parameters-dictionary-contains-a-null-entry-for-parameter-k-of-non-n
This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 5 years ago.
Hello Everybody Good day My English is not very good Poo Do not Look Mvc 5 New Start My Blog Site.
I got the error
I List Categories, I Provide Entrance to Other Areas
When I Select Photo When I Select Time
I uploaded the picture and I share the link. I am taking this mistake. Could you show me the way to this error? Thank you for your time
namespace MvcSite.Controllers
{
public class AdminMakaleController : Controller
{
MvcblogDb db = new MvcblogDb();
// GET: AdminMakale
public ActionResult Index()
{
var makale = db.Makale.ToList();
return View(makale);
}
// GET: AdminMakale/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: AdminMakale/Create
public ActionResult Create()
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi");
return View();
}
// POST: AdminMakale/Create
[HttpPost]
public ActionResult Create(Makale makale, string Etiket, HttpPostedFile Foto)
{
if (ModelState.IsValid)
{
if (Foto != null)
{
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFoto/" + newfoto;
}
if (Etiket != null)
{
string[] etiketdizi = Etiket.Split(',');
foreach (var i in etiketdizi)
{
var yenietiket = new Etiket { EtiketAdi = i };
db.Etiket.Add(yenietiket);
makale.Etiket.Add(yenietiket);
}
}
db.Makale.Add(makale);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
// GET: AdminMakale/Edit/5
public ActionResult Edit(int id)
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makales.KategoriId);
return View(makales);
}
// POST: AdminMakale/Edit/5
[HttpPost]
public ActionResult Edit(int id, HttpPostedFile Foto, Makale makale)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (Foto != null)
{
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFOTO/" + newfoto;
makales.Baslik = makale.Baslik;
makales.İcerik = makale.İcerik;
makales.KategoriId = makale.KategoriId;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makale.KategoriId);
return View(makale);
}
}
// GET: AdminMakale/Delete/5
public ActionResult Delete(int id)
{
var makale = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makale == null)
{
return HttpNotFound();
}
return View(makale);
}
// POST: AdminMakale/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
foreach (var i in makales.Yorum.ToList())
{
db.Yorum.Remove(i);
}
foreach (var i in makales.Etiket.ToList())
{
db.Etiket.Remove(i);
}
db.Makale.Remove(makales);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Try to use a DropDownListFor instead of a DropdownList. The error you mention means that you are having NULL in the SelectListItem. You should create a list of ListItem in the DropDownList.
(I'm not sure if I'm correct or not. I'm just trying to help quickly.)
hello I'm trying to pass the new posted value to a different view with the new value id at the url using RedirectToAction but I'm getting the wrong Url .
Just like here in SO ,that you get redirect to your Q. after submit.
the Url I'm suppose to get is http://localhost:1914/en/evntes/index/60
MyCode(Controler= VoosUp)
public ActionResult Create()
{
var viewModel = new LectureFormViewModel
{
Genres = _context.Genres.ToList(),
};
return View("Gigform", viewModel);
}
[Authorize, HttpPost]
public ActionResult Create(LectureFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
return View("Gigform", viewModel);
}
var lectureGig = new LectureGig
{
//Prametrest
};
_context.LectureGigs.Add(lectureGig);
_context.SaveChanges();
// return this.RedirectToAction( "events", (c=>c.Index(lectureGig.Id)); //Compiler Error
return RedirectToAction("index", "Events", new { id = lectureGig.Id });//Ok Id 60
}
Events/Index
public ActionResult Index(int id)//OK id=60
{
var lecturegig = _context.LectureGigs.Include(g => g.Artist)
.Include(g => g.Genre)
.SingleOrDefault(g => g.Id == id);
if (lecturegig == null)
return HttpNotFound();
var viewmodel = new GigDetailViewModel { LectureGig = lecturegig };
return View("index", viewmodel);
}
Url i'm getting :http://localhost:1914/en/VoosUp/Create
and the view is correct
// GET: /Product/Delete/5
public ActionResult Delete(int id)
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
//return View(data.Products.FirstOrDefault(p => p.ProductID == id));
return View(res);
}
//
// POST: /Product/Delete/5
// [HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
**public ActionResult Delete(Product producttodelete)**
{
try
{
// TODO: Add delete logic here
var res = (from r in data.Products where r.ProductID == producttodelete.ProductID select r).FirstOrDefault();
// var productto = data.Products.Single(p => p.ProductID == producttodelete.ProductID);
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
Here in the line "producttodelete" i am not getting any values it is cuming null.Rather than create,details,edit are working fine.... only delete not working.......I tried a lot
Assuming you are using strongly typed views, have you tried:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, Product productToDelete)
{
try
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
... or if you are not using strongly typed views:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
In either case, you need to provide an id parameter which you can then use to get your object from your datastore. The default route mapping in MVC2 (in Global.asax.cs) will take the ID from the post URL and map it to this parameter for you.
why not just get the id like you were in the rest instead of trying to get the whole model? it seems like you're just selecting using the id anyway. try this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id)
{
try
{
// TODO: Add delete logic here
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
// var productto = data.Products.Single(p => p.ProductID == producttodelete.ProductID);
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}