Binding Gridview with drop down list selection MVC 5 - asp.net-mvc-4

I have a drop down list (Cities) and on selection it should be able to bind a Grid View in MVC 5
i am able to bind the drop down list and grid view but unable to handle the select event of Drop Down list. I dont know how to proceed on this I dont want to use Jquery. Below is my code
// BELOW IS THE DROP DOWN LIST CODE
#using (Html.BeginForm("BindGridView", "FacebookConfig", FormMethod.Post, new { id = "Id" }))
{
#Html.DropDownList("Cities")
}
// ON SELECTION OF ABOVE I SHOULD BE ABLE TO BIND THE BELOW GRID VIEW
#if (Model != null)
{
foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.Keywords)
#Html.ActionLink("Edit", "Edit", new { id = item.Id })
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
// BELOW IS THE CODE IN CONTROLLER
public ActionResult Index()
{
var cities = So.BL.City.GetCities();
ViewBag.Cities = new SelectList(cities, "Id", "Name");
return View();
}
[HttpPost]
public ActionResult BindGridView(int id)
{
var filter = So.BL.FacebookFilter.SelectFBApprovalFilters(id);
return View(filter);
}

If you want to perform an operation on dropdown on change event you must go for javascript/jquery for handling the element events. To satisfy your requirement you may do as,
Create a <div> to hold the new grid view to be created with the id to select.
Create a partial view that generate the grid view.
Create a function either in jquery/javascript for dropdown list on change event.
From the function call an action method using ajax.
Create an action method which would do what ever the functionality you want to do and return the partial view with the model required for generating the grid view.
Finally on success method of ajax call, write the output response to the inner html of the <div>.
If definitely not going for jquery or javascript then do a post back and from the selected dropdown value in the post method fetch the data for grid view and bind it to the grid. Note here the form submission will not occur on dropdown selection must use a submit button. Also show the grid based Model if not null.
Choose which one you likely to adopt.

Related

Select dropdown value after post

I was hoping for some guidance on an issue I am having with preserving the value in a dropdownlist after post (razor)
I have a simple page:
#model testContingency.Models.ListByWardDD
#{
ViewBag.Title = "TestDropDowns";
}
<h2>TestDropDowns</h2>
<div>
#Html.DropDownList("HospModel", Model.Hospital, new { #onchange = "ChangeHospital(this.value)" })
#Html.DropDownList("WardModel", Model.Wards)
<script type="text/javascript">
function ChangeHospital(val) {
window.location.href = "/PatientListByWardDD/TestDropDowns?hospID=" + val;
}
</script>
</div>
here's the controller
public ActionResult TestDropDowns(int? hospID)
{
PASInpatientRepository pasRepo = new PASInpatientRepository();
var returnModel = new ListByWardDD();
var HospitalData = pasRepo.GetPatientHospitalsEnum();
returnModel.Hospital = pasRepo.GetHopspitalListItems(HospitalData);
var WardData = pasRepo .GetPatientWardsEnum(hospID);
returnModel.Wards = pasRepo.GetWardListItems(WardData);
ViewBag.HospSearch = hospID;
return View(returnModel);
}
In the controller PASInpatientRepository() communicates with a cache database. It passes back public IEnumerable < SelectListItem > GetHopspitalListItems. It calls stored procedures written within a cache database (same as sql stored procedures in essence). This is all working fine in its own crude way.
The issue I am having is that when I select the dropdownlist #Html.DropDownList("HospModel", Model.Hospital, new { #onchange = "ChangeHospital(this.value)" }) and the controller is called to refresh the Wards dropdown, I want to preserve the value I have selected in the hospital dropdown. I have tried a few different ways, but I admit, I'm a bit stuck. Most examples I found are for strongly typed.
As I mentioned, I'm new to MVC, but any advice on how to solve this issue, or suggestions on improving my code are greatly appreciated.
So I'm not sure what the Hospital property looks like but I'll make the assumption that each one has a unique ID.
Furthermore to bind the posted data to the view model you'll need to use forms in your view. To create the drop down list use the DropDownListFor-Helper. This way the data will be bound back to your Model after submitting the form.
So your view could look something like this
#model testContingency.Models.ListByWardDD
#{
ViewBag.Title = "TestDropDowns";
}
<h2>TestDropDowns</h2>
<div>
#using (Html.BeginForm("TestDropDowns", "YourController", FormMethod.Post))
{
#Html.DropDownListFor(x => x.HospitalID, Model.Hospital)
#Html.DropDownListFor(x => x.WardID, Model.Wards)
<input type="submit" value="send" />
}
</div>
Your ViewModel testContigency.Models.ListByWardDD must have at least the following properties
public class ListByWardDD {
public int HostpitalID { get;set; }
// the value of the SelectListItem-objects should be the hospital ID
public IEnumerable<SelectListItem> Hospital { get;set; }
public int WardID { get;set; }
// the value of the SelectListItem-objects should be the ward ID
public IEnumerable<SelectListItem> Wards { get;set; }
}
Once you post the form (for simplicity I added a button to send the form and left the javascript part out) the method TestDropDowns of your controller (which you need to fill in the BeginForm-Helper) will be called. That method expects expects an object of type ListByWardDD as a parameter and the framework will automatically populate the values for you.
[HttpPost]
public ActionResult TestDropDowns(ListByWardDD viewModel) {
// your code here, viewModel.HospitalID should contain the selected value
}
Note: After submitting the form the properties Hospital and Wards will be empty. If you need to display the form again, you need to repopulate those properties. Otherwise your dropdown lists are empty.
I tried my best to post valid code but I did not compile or test it.

how to populate a dropdownlist based on another dropdownlist selected value in mvc 4?

I have created two Drop Down List. On selecting a value from first dropdown list second dropdown list should be filled this is my code in View
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.DropDownList("Id", ViewData["Id"] as List<SelectListItem>, new { })
<button type="submit">next</button>
}
#Html.DropDownList("Id", ViewData["Id1"] as List<SelectListItem>)
When I click on next button second dropdown is getting populated. Same thing I want to do when I select a particular item from first list. I don't want to use jquery is there any way to do?
Or is there any way how I can generate postback when I select value from first list?
I think you can put the first dropdown inside a form and include the change attribute to this dropdown:
#{ Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("Id", ViewData["Id"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
#{ Html.EndForm(); }
Then, in the controller, you should include some code to populate the second dropdown.

Return value from a partial view loaded on a jquery dialog

I have a partialview "selectUser". On this partial view a user can search for other users. The user id will be stored in a hidden field or as a var on my view. I need to use this partial view in many places. Lets say I need to return the id of the selected user on the close event of my dialog. My question is, how do I make this partial view, loaded as a modal dialog with jquery ui, to retrun the selected value to its parent view? Is there a way to access the value directly from the parent view?
I think I follow what you are needing now. So on your button click you do an ajax call back to the server and include the destination field name in the call
$.ajax({
url: "#(Url.Action("Action", "Controller"))",
type: "POST",
cache: false,
async: true,
data: { destination: 'fieldName' },
success: function (result) {
$(".Content").html(result);
AttachScript();
Dialog.load();
}
});
On your controller send that field to the partial view through your view model or viewbag and on the partial view put that field name in a hidden field. then in your button click you should be able to do something like this (untested)
function AttachScript(){
$('.btnSubmit').on('click', function(){
var data = $('.sharedField').val();
$($('.HiddenField').val()).val(data);
});
}
which will set the value of whatever field is named in your hidden field to the data. Hopefully this helps.

value not populating to kendo dropdown

I have a MVC View with Kendo UI that binds value from a ListObject. When the data is fetched from xml file the Kendo Dropdown binds the value but the data is fetched from a table of a database its not binding the value to the dropdown. But the List which has values and returned to the bind function of Dropdown is haveing the values.
The values are binded in Json Format.
//Controller Code that returns value to Kendo Dropdown in View
public JsonResult BindTitles()
{
return Json(_title.GetTitle(), JsonRequestBehavior.AllowGet);
}
//Data Interface from Entity Framework
public partial interface ITitle
{
IList<tblTitle> GetTitle();
}
public IList<tblTitle> GetTitle()
{
List<tblTitle> tit = new List<tblTitle>();
tit = dbContext.GetTitle().ToList(); // Here the values are available in the "tit"
return tit;
}
Show the code of the view on which you configured your kendo dropdown. The controller code is not enough to give you the solution.

What ActionResult should you return to update just the ActionLink text?

I'm using MVC4 with Entity Framework and like many people I'm new to MVC and trying to get my head around the design patterns.
I have a partial view that displays a list of sessions followed by actionlinks allowing the authenticated member to book into the sessions.
Note: for clarity, I've chopped out most of the code, if a member is booked into a session, it displays "Booked" instead of the action link.
#using OnlineBookings.Website.Models
#{ DateTime currentDate = DateTime.MinValue.Date; }
<form method="post" action="~/Controllers/BookSessionController.cs">
#foreach (SessionsWithBookingInformation s in Model)
{
<p>#s.StartTime.ToString("t")
#s.Description
#Html.ActionLink(
"Book",
"BookSession",
new { sessionId = s.SessionId }
)
</p>
}
</form>
This then displays as part of a larger view:
The actionlinks pass the guid of the session to be booked through to the following function in my controller, which retrieves the memberId from the cookie and uses Entity Framework to create a booking for that member and session.
public ActionResult BookSession(Guid sessionId)
{
using (var db = new OnlineBookingsEntities())
{
// see if the member id is stored in a cookie
if (Request.Cookies["memberId"] != null)
{
var memberId = new Guid(Request.Cookies["memberId"].Value);
db.Bookings.Add(new Booking
{
BookingId = Guid.NewGuid(),
MemberId = memberId,
SessionId = sessionId,
BookingTime = DateTime.Now
});
db.SaveChanges();
}
}
// this refreshes the entire page
/// is there a better way to just replace the actionlink they clicked on?
return RedirectToAction("Index", "Home");
}
All this is working nicely and bookings are being effectively recorded.
But, I'm trying to figure is if the return from the BookSession function can just update the actionlink text.
Ideally, on success, I want to replace the ActionLink in my partial view with the word "Booked" and on failure I want to replace it with the failure condition like "Session full".
Or I could just update my partial view, because that will do the same thing.
Am I missing something simple here? Or, am I barking up entirely the wrong tree?
Your question is great and really well explained, but it's also a little vague since it's a bit of a "What should I do?" question. Here are a few options that might help you develop a solution.
Redisplay the same view. Return whichever view the user was on for them to submit the link. This will look like a simple refresh.
return View();
Submit the request via AJAX and update via a partial view. Put an id tag on a span or similar HTML element with an individual booking's details inside. Submit the request with AJAX, perhaps via #Ajax.ActionLink, and have your action return a partial view.
return PartialView("_OnlineBookingPartial", model);
Once your partial view is returned, update the specific booking with the data returned.
Use AJAX again, but return JSON. Another way might be that you use AJAX again but instead you return JSON and do something with it. You could, for example, return text in which you would replace Book with; i.e. "Session full" or "Booked!".
return new JsonResult
{
Data = "Booked!"
}
Personally, I'd probably use AJAX to update with a non-AJAX (non-Javascript) fallback.
You can do this by using #Ajax.ActionLink and checking if the request is AJAX or not inside your controller action.
if (Request.IsAjaxRequest) {
return PartialView("_OnlineBookingPartial", model);
}
return View();
This means that if the browser has Javascript enabled and supports AJAX, it will be used and the whole process will be seamless and instant for the user. If Javascript is disabled, the page will simply refresh.