I have a search page using MVC4 with Razor. Details as bellow:
Whole page is divided in to two part.
Left panel contains total 5 search section like search by product, search by city etc. Each section have check box list. So user can select multiple option from each section.
Search panel is a partial view with a submit button. As given below
#using (Html.BeginForm("ModelsList", "Model"))
{
<div class="ModelListSearch
Panel" style="width: 309px; float: left">
<div class="heading">
By Budget
<div class="clear">
</div>
</div>
<!--heading-->
<ul>
#{
for (int i = 0; i < Model.BudgetDescription.Count; i++)
{
<li>
#Html.HiddenFor(m => m.BudgetDescription[i].BudgetId)
#Html.HiddenFor(m => m.BudgetDescription[i].Description)
#Html.CheckBoxFor(m => m.BudgetDescription[i].Selected)#Model.BudgetDescription[i].Description
</li>
}
}
</ul>
Action methods are as below
public ActionResult ModelsList(int? brandId, int? bodyStyleId, int? fuelTypeId, int?
transmissionTypeId, int? budgetID)
{
// this is called when first time page is loaded
}
[HttpPost]
public void ModelsList(NewCarSearchContainer searchData)
{
// this is called on click of search button
}
On click of search button search result is shown in right panel.
When we click on search button it post whole search object (NewCarSearchContainer) to action method & we find out the selected item from this object & get data from DAL layer accordingly.
This page is working fine BUT problem is that URL does not updated as per user selected search option. I think as we are using post it does not update url. We can not used GET as GET pass all check box item as query string header which has a specific limit.
One option is using action link instead of submit button. But in that case i dont know how pass selected item of search panel to action method.
We need to updated URL as per selected search option to optimize SEO.
Please take a look of Datatable Jquery Grid. Click Here.
Related
I'm having a problem with bootstrap 4.3's pagination. I read the documentation, but nowhere is it explained how to bind the pagination bar to an actual list with items. I'm quite new to bootstrap, and MVC, so forgive me if i'm asking a very stupid question, but i just can't figure it out. Say i have an unordered list of elements (see the code below). These elements have form fields and so on, which are a part of the form, for which the page is about. I want to list every question (it's a survey) on its own, and have next and previous buttons below it, that navigate respectively to the next and previous question (item in the list) of the survey. However, as I said i really can't figure out how to do this. Would anyone have any idea how to help with this?
Here is the view (I cut the logic behind the form fields as I recon it won't be needed for this example.
#model cq.Models.EmptySurveyViewModel
<div class="container">
#using (Html.BeginForm("New", "Client", FormMethod.Post, new { role = "form" })) {
#Html.HiddenFor(m => m.Sequence, Model.Sequence)
#Html.AntiForgeryToken()
<h2>#Model.Name</h2>
<hr />
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#Html.HiddenFor(m => m.Name, new { #value = Model.Name })
<ul>
#for (int i = 0; i < Model.Questions.Count(); i++) {
<li>
//Some fields and logic here
</li>
}
</ul>
<button type="submit" class="btn btn-primary"><i class="fas fa-check"></i> End survey</button>
}
</div>
Thanks in advance!
depending on your UI scenario there could be a lot of solutions, if you want to show one question time it is even not necessary to use paging item, just use standard link/button to navigate to the next/previous question.
The important part is in the backend, you should order your data so you can navigate forward/backward according to the order field.
if you will have a list of questions listed then a navigation control is required, again, you should order your items and load only the amount of items to be listed in one page.
e.g.:
// Questions are ordered by date as an example
// P is current page number
// S is page size (the number of items to be displayed in one page)
// you should send P and S parameters to the method and get back the requested paged items.
var items = Questions.OrderBy(x => x.Date)
.Skip((P - 1) * S)
.Take(S)
.ToList();
Additionally, any pagination control needs total number of records to render page numbers accordingly, so you need to return the total number of records as well;
var totalItems = Questions.Count();
There is a lot more to consider, as search and filtering parameters, show/hide only relevant number of pages, navigate prev/next, first/last, change page size, etc..., but really I don't have much time to explain more here, for now you may refer to this article, hope it helps :)
can a Partial Views on mvc create view that is using a dropdown list that sends value from the dropdown list to a function that creates a list based on the dropdown list value selection, That is then stored in a view bag for the partial view.. Can this be done in mvc and can it be done on create view of a mvc form?
I can see how something this would work in the edit view because the dropdown list value has already been selected when the page loads.
But on a new Create view record nothing is selected so the list function has a null value
Are partial views only for forms that have data pre-populated in them?
Update:
I have a create view that was created by the visual studio wizard. It has both a post and get under the create. When the user in the create view. I have a dropdown list on the page form with other fields but on load of that new create page it is empty. Unfortunately for me I wanted my partial view to to get populated with a list of data that gets sent to a view bag after the user make a selection from the drop down list.
I think what I am asking to do can only be done with webforms as mvc can handle dynamic data all that well it seems. And since when the page loads the dropdown has no value.. the list can't built so there is a null value error as well as and empty list if I hard code a value in the drop down list.
Here is my Code in these different attempt threads with different veration of my code documenting my many attempts. As I have comcluded it is not possible sadly.
Can a Drop Down List Trigger A Partial View To Update on A Create View Form In mvc?
Null view bag and partial view
Populating Partial Views using mvc
Updating a Partial View in MVC 5
So with help from Matt Bodily You can Populate a Partial View in the create view triggered by a changed value in a drop down list using a view bag and something called Ajax. Here is how I made my code work.
First the partial view code sample you need to check for null data
_WidgetListPartial
#if (#ViewBag.AList != null)
{
<table cellpadding="1" border="1">
<tr>
<th>
Widget Name
</th>
</tr>
#foreach (MvcProgramX.Models.LIST_FULL item in #ViewBag.AList)
{
<tr>
<td>
#item.WidgetName
</td>
</tr>
}
</table>
}
Populating your View Bag in your controller with a function
private List<DB_LIST_FULL> Get_List(int? VID)
{
return db.DB_LIST_FULL.Where(i => i.A_ID == VID).ToList();
}
In your Create controller add a structure like this using the [HttpGet] element
this will send you data and your partial view to the screen placeholder you have on your create screen The VID will be the ID from your Drop down list this function also sends back the Partial View back to the create form screen
[HttpGet]
public ActionResult UpdatePartialViewList(int? VID)
{
ViewBag.AList = Get_List(VID);
return PartialView("_WidgetListPartial",ViewBag.AList);
}
I am not 100% if this is needed but I added to the the following to the ActionResult Create the form Id and the FormCollection so that I could read the value from the drop down. Again the Ajax stuff may be taking care if it but just in case and the application seems to be working with it.
This is in the [HttpPost]
public ActionResult Create(int RES_VID, FormCollection Collection, [Bind(Include = "... other form fields
This is in the [HttpGet] again this too may not be needed. This is reading a value from the form
UpdatePartialViewList(int.Parse(Collection["RES_VID"]));
On Your Create View Screen where you want your partial view to display
<div class="col-sm-6">
<div class="form-horizontal" style="display:none" id="PV_WidgetList">
#{ Html.RenderAction("UpdatePartialViewList");}
</div>
</div>
And finally the Ajax code behind that reads the click from the dropdown list. get the value of the selected item and passed the values back to all of the controller code behind to build the list and send it to update the partial view and if there is data there it pass the partial view with the update list to the create form.
$(document).ready(function () {
$('#RES_VID').change(function ()
{
debugger;
$.ajax(
{
url: '#Url.Action("UpdatePartialViewList")',
type: 'GET',
data: { VID: $('#RES_VID').val() },
success: function (partialView)
{
$('#PV_WidgetList').html(partialView);
$('#PV_WidgetList').show();
}
});
This many not be the best way to do it but this a a complete an tested answer as it work and it is every step of the process in hopes that no one else has to go through the multi-day horror show I had to go through to get something that worked as initially based on the errors I thought this could not be done in mvc and I would have to continue the app in webforms instead. Thanks again to everyone that helped me formulate this solution!
No, partial views do not necessarily have to be strongly typed, if that's your question. You can have a partial view with just html markup.
I am creating a voting mechanism for my MVC application. user will be able to vote only after loged in. I have totally 3 tables tblQuestions(to populate the questions), tblAnswers(to populate the answers), tblQuestionAnswerUserResponses (to populate the user response.)tblAnswers have relation with tblQuestions. I have used the following code in the container in the HttpGet. This is my controller code.
[HttpGet]
[ActionName("VotingResult")]
public ActionResult VotingResult(int personid)
{
List<Voting_Questions> QuesList = EpDObj.PopulateQuestions(); //Populate the list of questions
CountofQuestionsDisplayed = QuesList.Count;
ViewBag.Questions = QuesList; // Storing the list of questions in the viewbag
List<Voting_Answers> Answers = EmcObj.Voting_Answers.ToList(); //Populate the list of answers
return View(Answers);
}
I am using the Voting_Answers as model in my view My view is
#model IEnumerable<EmployeeManagementDAL.Voting_Answers>
<h2>VotingResult</h2>
#using (Html.BeginForm())
{
<div>
#foreach (var a in ViewBag.Questions)
{
<h4>#a.Questions</h4>
<div>
#foreach (var b in Model)
{
if (b.QuestionsID == a.id)
{
#Html.RadioButton(b.AnswersOptions, new {Answerid= b.id, Questionid=a.id }) #b.AnswersOptions
}
}
</div>
}
</div>
<br/>
<div >
<input type="submit" value="Vote Now!!" onclick="return confirm('Are you sure you want to submit your choices?');"/>
</div>
}
When the user go to this page for the very first time there will be no options selected. after selecting the options the values an clicking Save button will save the details to the third table and then he comes out of that page. Now if for the second time he reaches that page for editing, I want my page to render with those values in my tblQuestionAnswerResponses i.e I guess my model class of tblQuestionAnswerResponses to be used. In that case can i use the same page for both cases i.e when the user vists the page for first time and also when second time the page is visited. Can I use multiple Model in MVC based on conditions in my View.
Your ActionName attribute is unnecessary, as you have specified the same name that your action already has.
It would be cleaner to use a ViewModel instead of using the ViewBag. For starters, you'll get strong typing in your view, and it will also lend itself to easier testing.
If you make a ViewModel that represents what you want your view to display, then you can map back and forth between it and your domain models in your controller actions, and let them do the heavy lifing.
I have a form in my razor view which works exactly as it should. I select values from the drop down and press the submit button and it return to me a paginated set of results. All well and good.
#using (Html.BeginForm())
{
int index = 0;
foreach (var type in #Model.AttributeTypes)
{
#Html.DropDownListFor(m => m.SelectedAttributeValueIds[index], Model.AttributeValuesList[Convert.ToInt32(#type.Value)], "Filter by " + type.Text)
index++;
}
<input type="submit" value="Filter"/>
}
The problem is that at the bottom of the page, outside of the form I want a Show all button/link. Pressing this button should essentially do the same thing that the above submit button does. In other words I'd like this Show all button to show all of the results of the last query (or the currently selected values in the dropdowns - not too bothered which) without pagination. I can do the no pagination bit, that is easy. What I want to know is how will my button/link get the values from the dropdown from outside of the form and submit that form?
You can use javascript/jquery to submit the form on click of that button.
$('#formId').submit();
To wire this up you could do the following on your document ready script:
$('#buttonId').click(function() {
$('#formId').submit();
});
Use javascript to read information on the dom element you need to grab the info and them submit an ajax request.
For some reason I'm stuck on this. I need to filter results from a View based on a DropDownList in the same view. The basic idea is this: I have a list of providers that belong to various partners, but the provider list contains ALL the providers together (for all partners). I need to be able to display the providers by partner when someone wants to see just that partner (otherwise, the default listing will be ALL providers). My view currently is the "default" (showing all), but for some reason Im sitting here staring at the monitor (for the last 2 hours!) trying to figure out how to filter these results.
Any suggestions where to start/how to do it?!
EDIT: If you want to do this with jQuery and AJAX (which will provide a better user experience because only the subdivisions list will refresh), see this tutorial.
If I understand correctly, you basically want to do a WebForms-style postback.
Let's say you have a control with countries and country subdivisions (e.g. states, provinces, etc). When the country changes, you want the appropriate subdivisions to display.
So this would be view:
<% using (Html.BeginForm()) { %>
<%=Html.DropDownList("Address.CountryId", new SelectList(Country.GetAll(), "Id", "Name"), new { onchange = "this.form.submit();" })%>
<%=Html.DropDownList("Address.CountrySubdivisionId", new SelectList(CountrySubDivision.GetByCountryId(Model.CountryId), "Id", "Name"))%>
<input type="submit" name="btnSubmit" value="Submit"/>
<%} %>
This is the key to getting the dependent list to filter:
new { onchange = "this.form.submit();" }
And in the controller, you'd have something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Index(string btnSubmit)
{
if (btnSubmit == null)
{
// return the view displayed upon GET
}
else
{
// process the submitted data
}
}
In the above code, if the form submission was triggered by changing the value in a dropdown, btnSubmit will be null. Thus, the action you are POSTing to can tell whether or not the user meant to finalize her changes.
To add upon the earlier answers.
To create a drop down (in ASP .NET MVC 3) I did the following:
Add code to Index.cshtml
#using (Html.BeginForm())
{
#Html.DropDownList("EmployeeId", (SelectList)ViewData["EmployeeId"])
<input type="submit" name="btnSubmit" value="Submit"/>
}
Add code to YourModelNameController.cs in the default ActionResult for Index()
public ActionResult Index()
{
//create a selectlist
var employeeList = from el in db.Employee select el;
ViewData["EmployeeId"] = new SelectList(employeeList, "EmployeeId", "TmName");
return View(modelName);
}
There are many ways to skin this cat. Here's one.
Enclose your DropDownList in a form with METHOD=GET.
<form action="" method="get">
<select name="provider">
<option>1</option>
<!-- etc -->
</select>
</form>
Then, in you controller, filter based on the value of provider that was passed in. Remember to treat it as a Nullable parameter so that you can have some kind of behavior when it's empty.
Without posting some of your current code, it's tough to get much more specific than that.
Let's assume that you're probably passing a model to the view and that model is a list or IEnummerable of partners. What you want to do is restrict the list. In order to do that add a drop down list in the view and fill it with some possible partners. This can be done either by putting a list in ViewData or expanding the model passed back to the view. Both have advantages. Now when you change the drop down reload the page but append a parameter which is the filter. In the controller check for that parameter in the action, if it isn't present then return an unfiltered list, if it is then apply a filter and return the list. The view will just dumbly display whatever you give it.
As for the filtering you might want to try using LINQ.
You probably want a parameter to your controller action, maybe a (nullable?) id of the provider, to filter the results already when you get them from DB. Then just use the same view to list them, and request a new list if the dropdownlist changes.
Best solution I know is that one.
http://gridmvc.codeplex.com/SourceControl/latest