I'm new to asp.net mvc. I have index method with parameter id :
public ActionResult Index(int id)
{
var dc = new ServicesDataContext();
var query = (from m in dc.Mapings
where m.CustomerID == id
select m);
// var a = dc.Customers.First(m => m.CustomerId == id);
// ViewData.Model = a;
// return View();
return View(query);
}
Now when I try to redirect to index from edit i get an error " The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'MVCServices.Controllers.CustomerserviceController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
[HttpPost]
public ActionResult Edit( FormCollection form)
{
var id = Int32.Parse(form["CustomerServiceMappingID"]);
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
TryUpdateModel(serviceToUpdate, new string[] { "CustomerID", "ServiceID", "Status" }, form.ToValueProvider());
if (ModelState.IsValid)
{
try
{
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
datacontext.SubmitChanges();
//return Redirect("/Customerservice/Index/qw");
return RedirectToAction("Index", new { qw = qw });
}
catch{
}
}
return View(serviceToUpdate);
}
This is the View:
#Html.ActionLink("Back to List", "Index")
The id in the Index method turns out to be the customerid fetched from another controller while id in Edit is from another table.Can you please let me know the mistake I've been doing and how to solve it?
Do this in the Edit action:
return RedirectToAction("Index", new { id = qw });
Related
I am getting the value from dropdown to controller but when it goes back to View it returns Null
SCREENSHOT OF VIEW:-
SCREENSHOT OF CONTROLLER:-
public ActionResult Index(int departmentID)
{
ViewBag.dropdowndetail = null;
var strDDLValue = departmentID;
if (strDDLValue == null)
{
return HttpNotFound();
}
else
{
var emp = db.employees.ToList().FirstOrDefault(x=>x.depId==departmentID);
return View(emp);
}
}
ERROR:
I get it right
My viewbag was not getting any value in Post method so that why in View it was getting null Exception
I call my viewbag in Post method and give it the value.
change the following code with this.
public ActionResult Index(int departmentID)
{
var strDDLValue = departmentID;
if (strDDLValue == null)
{
return HttpNotFound();
}
else
{
var emp = db.employees.Where(x=>x.depId==departmentID).ToList();
ViewBag.dropdowndetail = db.departments.Distinct().ToList();
return View(emp);
}
}
You can use keyvalue approach in controller
ViewBag.dropdowndetail = db.departments.Distinct().Select(x => new KeyValuePair<int, string>(x.depid, x.DepartmentName));
and in View use ViewBag like this
#Html.DropDownListFor(model => model.depid, new SelectList((IEnumerable<KeyValuePair<int, string>>)ViewBag.dropdowndetail , "key", "value"), "--Select Departments--")
I have an entity model that has a collection property (many-to-many relationship) of Users signed up for the application.
in the Edit view I used implicit model binding to edit task object with the single properties (Title, DueDate, etc..) and Users (checkboxes) :
public ActionResult Edit([Bind(Include = "Id,Title,Description,DueDate,Status")] UserTask task, string[] asndUsers/*users IDs*/)
{
if (ModelState.IsValid)
{
task.Users = new List<ApplicationUser>();
if (asndUsers != null)
{
foreach (var userId in asndUsers)
{
var user = context.Users.Find(userId);
task.Users.Add(user);
}
}
context.Entry(task).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
return View(task);
}
but this didn't work, the single properties was updated but the Users couldn't be updated.
I then used the explicit model binding
var task = context.Tasks.Include(t => t.Users).SingleOrDefault(s => s.Id == id);
task.Users = new List<ApplicationUser>();
foreach (var userId in asndUsers)
{
var user = context.Users.Single(u => u.Id == userId);
task.Users.Add(user);
}
if (TryUpdateModel(task, "", new string[] { "Title", "Description", "DueDate", "Status" }))
{
context.SaveChanges();
return RedirectToAction("Index");
}
it works, but have no idea what it did that implicit binding didn't
All Im trying to do is get my url to have the blogid appending to it much like the following...
http://localhost/blog/blogpost/17
Here is my Controller...
public ActionResult BlogList(){ return View(_repository); }
public ActionResult BlogPost(string id)
{
ViewData["id"] = id;
if (ModelState.IsValid)
{
return RedirectToAction("BlogPost", new { id = id });
}
return View(_repository);
}
Now here is my route.config maproute
routes.MapRoute(
"MyBlog", // Route name
"blog/{action}/{id}", // URL with parameters
new { controller = "Blog", action = "blogpost", id =
UrlParameter.Optional } // Parameter defaults
);
Now I can get the url to appear when I click on a blog in the blogList. The page doesn't display the blog it displays a redirect loop message. If I omit the following code ...
if (ModelState.IsValid)
{
return RedirectToAction("BlogPost", new { id = id });
}
then I can display the blog. The url wont have the id value. Like this...
http://localhost/blog/blogpost/
What am I doing wrong?
The following code should work with your route:
// http://localhost/blog/bloglist
public ActionResult BlogList()
{
return View(_repository); // show all blog posts
}
// http://localhost/blog/blogpost/1
public ActionResult BlogPost(int? id = null)
{
if (id.HasValue == false || id.Value < 1)
{
// redirect to 404 page or BlogList
throw new NotImplementedException();
}
var blogPostObj = _repository.Find(id.Value);
if (blogPostObj == null)
{
// again redirect to 404
throw new NotImplementedException();
}
return View(blogPostObj);
}
Remove the BlogList() which takes 0 parameter
public ActionResult BlogList(){ return View(_repository); }
This is not required, since your id is type of string which can be null
The below code can be help you
public ActionResult BlogPost(string id)
{
var model=new ModelObject();
if(id!=null)
{
var model=Blogs.Find(id); //find it from repo
return View(model);
}
return View(model);
}
From your code it does not look like the id field is optional. Therefore I would change the route.
routes.MapRoute(
"MyBlog", // Route name
"blog/blogpost/{id}", // URL with parameters
new { controller = "Blog", action = "blogpost" },
new { id = #"(\d)+"} //ensures value is numeric.
);
RouteData.Values["id"] + Request.Url.Query
I am trying to add filter by ID for the following:
public ActionResult Index()
{
var model = from o in new MainDBContext().OffLinePayments
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
What I would like to do is the following:
public ActionResult Index(long? id)
{
if (id != null)
{
var model = from o in new MainDBContext().OffLinePayments
**Where Assigned_ID == id**
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
else
{
var model = from o in new MainDBContext().OffLinePayments
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
}
try
var model = from o in new MainDBContext().OffLinePayments
where o.Assigned_ID == id
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
If I understand correctly, your problem is that the compiler doesn't let you write where o.Assigned_ID == id in the query.
That's because id is a Nullable<long>, which is not implicitly convertible to a long (which OffLinePayment.Assigned_ID presumably is).
You need to write where o.Assigned_ID == id.Value instead. Take a look at what the Value property does so that you don't get any surprises.
A cleaner, shorter and much more readable syntax would look like this:
public ActionResult Index(long? id){
using (var ctx = new MainDBContext())
{
var entities = ctx.OfflinePayments.Where(e => !e.HasValue || e.Assigned_ID == id.Value);
var model = entities.Select(e => new EditOfflinePayment { ID = e.ID, Amount = e.Amount }).ToList();
return View(model);
}
}
I have a link in my action like this
<%: Html.ActionLink("View Data","Index","MyItem", new {itemId=Model.itemId}, null)%>
now in my newItem controller in its index action how do I retrieve this itemId, so far I have tried
this
public ActionResult Index()
{
RouteData rd = this.RouteData;
var list = from p in rd.DataTokens.Where(p => p.Key == "itemId") select p;
int? id = null;
if (list.Count() > 0)
id = Convert.ToInt32(list.Single().Value);
if (id.HasValue)
{
return View(from a in _Service.List().Where(a => a.ApplicantId == id.Value) select a);
}
else
return View(NORECORDVIEW,);
}
and also this
HttpRequestBase rd = this.Request;
var list = from p in rd.QueryString.AllKeys.Where(p => p. == "itemId") select p;
int? id = null;
if (list.Count() > 0)
id = Convert.ToInt32(list.Single().Value);
if (id.HasValue)
{
return View(from a in Service.List().Where(a => a.ApplicantId == id.Value) select a);
}
else
return View(NORECORDVIEW);
however none of this return the correct value.
In mvc1 we could easily handle that directly but how do you do this in mvc2 please.
You can do this much more easily:
public ActionResult Index(int itemId)
Not only is this 1/10th the code, it's far more easily tested.