I have following entry in Global.asax:
routes.MapRoute(
"Email",
"Email/{emailId}",
new { controller = "Email", action = "Index", emailId = UrlParameter.Optional}
);
routes.MapRoute(
"Details",
"Details/{rmaid}/{orderid}",
new { controller = "Details", action = "Index", rmaid = UrlParameter.Optional, orderid = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);
routes.MapRoute(
"Logout", // Route name
"Logout/", // URL with parameters
new { controller = "Home", action = "Logout"} // Parameter defaults
);
The very last for Logout is giving me 404.
My home Controller have following entry:
public ActionResult Logout()
{
Session.Abandon();
return Redirect("/");
}
First enter your logout route and then the default route.
But if you don't use that logout route you could also navigate to Home/Logout.
Related
this is my Get actionresult :
public ActionResult Add()
{
ViewData["categoryList"]= _categoryRepository.GetAllCategory().
ToSelectList(c => c.Id, c => c.Name);
return View("Add");
}
this my razor that render the categoryList , and I have no trouble with that !
<div>
#Html.LabelFor(b => b.Category)
#Html.DropDownList("Category", ViewData["categoryList"] as IEnumerable<SelectListItem>)
#Html.ValidationMessageFor(b => b.Category)
</div>
finally after submitting the page , category select send via null value to post this action
[HttpPost]
public ActionResult Add(BlogPost blogPost)
{
if (ModelState.IsValid)
{
blogPost.PublishDate = DateTime.Now;
_blogPostRepository.AddPost(blogPost);
_blogPostRepository.Save();
return RedirectToAction("Add");
}
return new HttpNotFoundResult("An Error Accoured while requesting your order!");
}
could anybody tell me why ??
controller
public ActionResult Add()
{
ViewBag.CategoryList = new SelectList(_categoryRepository.GetAllCategory(), "Id", "Name");
// you dont need the specify View name
// like this: return View("Add")
// you need to pass your model.
return View(new BlogPost());
}
view
#Html.DropDownListFor(model => model.CategoryId, ViewBag.CategoryList as SelectList, "--- Select Category ---", new { #class = "some_class" })
controller post action
[HttpPost]
public ActionResult Add(BlogPost blogPost)
{
if (ModelState.IsValid)
{
blogPost.PublishDate = DateTime.Now;
_blogPostRepository.AddPost(blogPost);
_blogPostRepository.Save();
// if you want to return "Add" page you should
// initialize your viewbag and create model instance again
ViewBag.CategoryList = new SelectList(_categoryRepository.GetAllCategory(), "Id", "Name");
return View(new BlogPost());
}
return new HttpNotFoundResult("An Error Accoured while requesting your order!");
}
I want to add another dropdownlist. The below code works for one dropdown, but how would I add one for Categories?
public ActionResult Create()
{
var ddl = new Users();
ddl.DropDowns = userRepository.Getddl("Departments").Select(c => new SelectListItem
{
Value = c.DropdownID.ToString(),
Text = c.DropdownText
});
ViewData["ListofProfiles"] = new SelectList(ListofProfiles, "Value", "Text");
return View(ddl);
}
Try to avoid the ViewData approach.Switch to Strongly typed way of doing this. Add another property to your View Model to carry one more dropdown items
public class User
{
public int SelectedCountry { set;get;}
public int SelectedProfile { set;get;}
public List<SelectListItem> Countries {set;get;}
public List<SelectListItem> Profiles {set;get;}
public User()
{
Countries =new List<SelectListItem>();
Profiles =new List<SelectListItem>();
}
}
Now set the collection in your GET action
public ActionResult Create()
{
var vm=new User();
vm.Countries=GetCountryItems();
vm.Profiles=GetProfileItems();
return View(vm);
}
Where GetCountryItems and GetProfileItems are 2 methods which returns a list of SelectListItem objects for countries and Profiles from db.
Do not make your controllers FAT. Just keep it simple and clean. Move away your code which fetch data from repository to a different layer. Easy to read and maintain :)
And in your strongly typed view,
#mode User
#using(Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedCountry,
new SelectList(Model.Countries, "Value", "Text"), "Select")
#Html.DropDownListFor(m => m.SelectedProfile,
new SelectList(Model.Profiles, "Value", "Text"), "Select")
<input type="submit" />
}
I have a generic list method that returns a CategoryID and CategoryName.
I have spent enough time researching and cant seem to put it together. I very new at MVC.
Here is my DropdownList Method in a repository. I get back the data... So far so good.
public List<DropdownList> GetDDl()
{
return catDDL;
}
Here is my CONTROLLER CODE(attempt at it)
IEnumerable<SelectListItem> liCat =
userRepository.Getddl().Select(c => new SelectListItem
{
Value = c.DropDownID.ToString(),
Text = c.DropDownText
}
ViewBag.catItems = new SelecList(liCat,"Value","Text");
Here is my VIEW
#Html.Dropdownlist("catItems","Select Category)
Try to avoid dynamic stuff like ViewBag and ViewData. Use strongly typed views.
ViewModel is just a POCO class which we will use to transfer data between your view and the action method. It will be specific to the view.
ex : if you want to create a view which creates a product. So create a viewmodel like this
public class Product
{
public string Name { set;get;}
public IEnumerable<SelectListItem> Categories{ get; set; }
public string SelectedCategoryId { get; set; }
//Other Properties as needed
}
now in your GET action method, you create an object of this view model and initialize the values and send to the view.
public ActionResult Create()
{
var vm=new Product();
vm.Categories=userRepository.Getddl().
Select(c => new SelectListItem
{
Value = c.DropDownID.ToString(),
Text = c.DropDownText
});
return View(vm);
}
Now make your view strongly typed to our Product class and use the Html.DropDownListFor helper method.
#model PersonsProduct
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedCategoryId,
new SelectList(Model.Categories,"Value","Text"), "Select")
<input type="submit" value="save" />
}
Now in your HttpPost , you can get the form values like this
[HttpPost]
public ActionResult Create(Product model)
{
if(ModelState.IsValid)
{
//check model.SelectedCategoryId
//save and redirect
}
//to do :reload the dropdown again.
return view(model);
}
Should just be:
Controller:
IEnumerable<SelectListItem> liCat = userRepository.Getddl().Select(c => new SelectListItem
{
Value = c.DropDownID.ToString(),
Text = c.DropDownText
}
ViewBag.catItems = liCat
View:
#Html.Dropdownlist("catItems", ViewBag.catItems)
I'm trying to get the drop down list to have my item selected when there is an item, but it never does. I've Googled this and tried many different methods, but they all seem to use a ViewModel containing the list instead of using ViewBag, but I would like to stick to the ViewBag if possible.
My controller:
[HttpGet]
public ActionResult Index(int? id)
{
ViewBag.SelectList = new SelectList(rep.GetItemList(), "id", "type");
if (id.HasValue)
{
var model = rep.GetItemByID(id.Value);
if ( model != null )
{
return View(model);
}
}
return View();
}
My View:
<div class="editor-field">
#Html.DropDownListFor(model => model.itemID, (SelectList)ViewBag.SelectList)
#Html.ValidationMessageFor(model => model.itemID)
</div>
This doesn't have my item selected in the DropDownList, and I've also tried having a list in the ViewBag and then constructing the SelectList in the View, which some posts say should solve the problem:
<div class="editor-field">
#Html.DropDownListFor(model => model.itemID, new SelectList(ViewBag.SelectList, "id", "type", Model.itemID))
#Html.ValidationMessageFor(model => model.itemID)
</div>
But none of it seems to work. So I was wondering if there is anyone where that is able to spot what I'm doing wrong?
make sure your itemID property is set in the model you are passing to the view
if (id.HasValue)
{
var model = rep.GetItemByID(id.Value);
model.itemID=id.Value;
return View(model);
}
I would try setting the selected value from the begining since SelectList is immutable.
[HttpGet]
public ActionResult Index(int? id)
{
if (id.HasValue)
{
ViewBag.SelectList = new SelectList(rep.GetItemList(), "id", "type", id );
var model = rep.GetItemByID(id.Value);
if ( model != null )
{
return View(model);
}
}
else
{
ViewBag.SelectList = new SelectList(rep.GetItemList(), "id", "type");
}
return View();
}
In your View use it like this:
#Html.DropDownListFor(model => model.itemID, (SelectList)ViewBag.SelectList, "Please select...")
I have a view where a user will enter an ID that will be passed to a controller method which will then populate a view containing the related patient record.
I am new to MVC and have been unable to get the ID from the textbox and pass it to the controller method. I appreciate any help.
In my view:
#model Final.Models.Patient
#Html.TextBoxFor(model => model.Patient_ID)
#Html.ActionLink("Patient", "Details", new { id=???? })
In my controller:
public ViewResult Details(decimal id)
{
Patient patient = db.Patients.Single(p => p.Patient_ID == id);
return View(patient);
}
Thanks.
I was able to make it work with the following:
#using (#Html.BeginForm("Details", "Patient")) {
#Html.TextBoxFor(model => model.Patient_ID)
<input type="submit", value="Submit"/>
public ActionResult Details(Patient _patient)
{
decimal id = _patient.Patient_ID;
Patient patient = db.Patients.Single(p => p.Patient_ID == id);
return View(patient);
}
Is jQuery method acceptable for you? You can assign an id to the textbox, and then get the value (id entered by user) and then submit to your controller using $.ajax
#Html.TextBoxFor(model => model.PatientID, new { id = "patient"})
$.ajax({
url: '/Home/Details',
type: 'POST',
data: { id: $('#patient').val()},
async: false,
success: function (result) {
alert('success!');
}
});
Hope this help you :)
receive the model in ActionResult instead
#model Final.Models.Patient
#usign (#BeginForm("Details","Controller"){
#Html.TextBoxFor(model => model.Patient_ID)
#Html.ActionLink("Patient", "Details", new { id=???? })
<input type="submit", value="Submit"/>
}
in your controller
[HttpPost]
public ActionResult Details(Patient _patient)
{
decimal id = _patient.Patient_ID
Patient patient = db.Patients.Single(p => p.Patient_ID == id);
return View(patient);
}