i have a textbox with button search.
i would like to search my database of input text from textbox and give result out in one view.
Could you please give me link or help me how its possible to implement?
I have no idea what i shoul to do that.
If you want to show the result in the same view page as that of the search criteria text box, the better approach will be to go with JQuery form post. And from the corresponding controller you can get back the JSON result and bind it to the grid, if you are using any third party grid.
The posting mechanism will be :
<div>
<input type="text" id="txtSearchText" value=""/>
<input type="button" id="btnSearch" value="Search"/>
</div>
<script type="text/javascript">
$("#btnSearch").click(function(){
var formPost={ SearchText : $("#txtSearchText").val()};
//The above SearchText parameter name should be same as property name in the Model class.
$.post("/SearchController/Search",formPost,function(data){
if(data)
{
//Here based on your development methodology, either build a table by
//appending a row for each result Or bind to a grid, if you are using
//any third party control
}
});
});
</script>
Controller Code :
public class SearchController
{
public ActionMethod Search(SearchModel searchCriteria)
{
SearchResultModel result= //Get the search results from database
return new JsonResult{Data=result};
}
}
Model class:
public class SearchModel
{
public string SearchText{get;set;};
}
Related
This is a follow on to similar question but taking suggestions into account.
Render part of page on dropdown selection
I have a chart on my main view which I would like to update partially when a dropdown selects different values.
The page renders correctly the first time, but when I select a new value in the dropdown, then I think the .submit script is failing in the script .submit() because when I put a break on window.submitAjaxForm it is never reached.
_PnlChart.cshtml
<img src="#Url.Action("CreateTraderPnlChart3")" width="600" height="600" align="middle" vspace="50" />
My mainview Index.cshtml:
<div class="w3-half">
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#using (Ajax.BeginForm("GetEnvironment",
new RouteValueDictionary { { "Environment", "" } }, new AjaxOptions() { UpdateTargetId = "ExportDiv" }, new { id = "ajaxForm" } ))
{
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"],
new
{ onchange = "submitAjaxForm()" })
}
</script>
<script type="text/javascript">
$('form#ajaxForm').submit(function(event) {
eval($(this).attr('onsubmit')); return false;
});
window.submitAjaxForm = function(){
$('form#ajaxForm').submit();
}
</script>
</div>
My controller:
public ActionResult PeriodSelection(string dropdownlistReturnValue) // dont know what dropdownlistReturnValue is doing?
{
Session["Period"] = dropdownlistReturnValue;
return PartialView("~/Views/Employee/_PnlChart.cshtml");
}
This line in your code,
eval($(this).attr('onsubmit')); return false;
I am not sure what you were intending to do here. But from your question, i assume you wanted to do a form submission. But that line will not submit the form. The expression $(this).attr('onsubmit') is going to return undefined as your form does not have an onsubmit attribute defined.
But you already have the form submit code in your other method (submitAjaxForm). So if you simply remove the $('form#ajaxForm').submit handler (apparently it does not do anything useful), your code will work. When you change the dropdown, it will make an ajax form submission.
But your form action is set to GetEnvironment action method. That means your ajax form submission will be to that action method. In your question you have a different action method which returns the updated chart content. It does not makes sense!
I personally prefer to write handwritten ajax calls instead of relying on the ajax action helper methods. The below is the code i would probably use (Except the dropdownlist code. read further)
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"], new
{ data_charturl = Url.Action("PeriodSelection","Home")})
Now listen to the change event of the SELECT element.
$(function(){
$("#PeriodSelection").change(function(){
var v = $(this).val();
var url=$(this).data("charturl")+'?dropdownlistReturnValue='+v;
$("#ExportDiv").load(url);
});
});
You should consider using the a view model to pass the Dropdownlist data. Why not use the DropDownListFor helper method ? It looks much clean, Mixing a lot of C# code (See all the session casting and all.) makes it kind of dirty IMHO.
I have a single page ASP.NET MVC 4 application which should display charts. Each chart (dotnetHighcharts) is contained in a single partial view with its own model.
Now I want to be able to display multiple charts on a single page, each with its own model, rendered in a partial view.
My controller looks like this:
public class ReportController : Controller
{
[HttpGet]
public ActionResult Display(Guid? id)
{
var viewModel = PrepareViewModel(id);
return View(viewModel);
}
[HttpPost]
public ActionResult DisplayChart(Guid? id)
{
var viewModel = PrepareViewModel(id);
return PartialView("Partial_ChartView", viewModel);
}
}
The partial view looks like this:
#model MobileReports.Models.ReportViewModel
#Model.Chart
The main view has this code:
#model IEnumerable<MobileReports.Models.ReportViewModel>
#{
ViewBag.Title = "Display";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="chartContainer" style="float:left">
#{Html.RenderPartial("Partial_ChartView");}
</div>
<div id="secondChartContainer" style="float:right">
#{Html.RenderPartial("Partial_ChartView");}
</div>
The Model itself contains only a rendered chart and a few infos about it.
My problem is, I don't know if I am doing it right. The mainview has to know which charts are already displayed on the page, so that I dont display the same chart twice. In the initial load, I somehow have to tell the partialviews which charts are already being displayed on the page. How can I do that?
Also how do I keep multiple models on the main view?
-edit-
The controller action DisplayChart(Guid? id) is used inside the partialView from a javascript function:
function displayNextReport() {
// try to find a report that is not displayed already
var diff = $(availableReports).not(displayedCharts).get();
if (diff.length > 0) {
// remove old chart data
if ($("#chart_container").highcharts() !== undefined) {
$("#chart_container").highcharts().destroy();
}
// load the new report
$("#chart_container").load('#Url.Action("DisplayChart", "Report")', { id: diff[0] });
}
}
Note: This does not work right now. I need to pass an argument that tells the DisplayChart() method which chart to load next. For this, I need to know which charts are currently diplayed.
My code is most likely very wrong and messed up. I think it is best to just describe what I want to achieve:
I want to have a View that displays multiple partial views of the same type. Each partial view has to know what the other partial view are currently displaying. Thats all I want to do..
I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
I am using also Entity Framework and Code First Method.
In a view Index, I have a DropDownList Gamme. I define its item selected in my view, like this :
public string SelectedProfile_Ga { get; set; }
In this view, I have a button Appliquerthat took me to another view Application.
<input type="button" value="Appliquer" id="appliquer" onclick="window.location = 'ProfileGa/Application'"/>
In the view Application, I have a button submit Appliquer.
<input type="submit" value="Appliquer" id="appl" />
When I click on Appliquer, I want save the value selected in my DropDownList Gamme in my base.
The problem is that this value is passed NULL when i change the view (exit page Index and open Application).
I find that with Debugging.
The Controller action :
[HttpPost]
public ActionResult app(FlowViewModel model)
{
Famille fam = new Famille();
fam.ID_Gamme = model.SelectedProfile_Ga;
db.Familles.Add(fam);
db.SaveChanges();
return RedirectToAction("Application");
}
Note :
I didn't forget this in the Application:
<% using (Html.BeginForm("app", "ProfileGa")) { %>
ProfileGa is the name of my controller.
For starters, your dropdown is in the Index view, and the selection is happening there. Then you're redirecting to ProfileGa/Application and leaving this information behind.
I would change this button:
<input type="button" value="Appliquer" .. etc
to a <submit>, and wrap the code with the dropdown in one of these:
using (Html.BeginForm("Application", "ProfileGa")) {
and add a Post version of Application
[HttpPost]
public ActionResult Application(FlowViewModel model)
{
// Do whatever
return View(model);
}
Then when you get to the Application view, it should still have the same information as it left Index with.
To check this is working, put a breakpoint at return View(model); and look at the model's contents.
However, posting null from the view probably means that something is wrong inside your <% using (Html.BeginForm("app", "ProfileGa")) { %> statement, so if the above doesn't do anything, post the code from your `Application' view.
I have a dropdownlist that is being populated by a sql server, I am using Visual Studio 2010, cshtml, with razor as well as using the MVC pattern to create this project. What I am trying to do is when someone selects a value from the dropdown list on change it will update the page with information about that book.
I need help with the three things below:
user selects a book from the dropdownlist how to get the Book Name back to the controller
The server (retrieve the information from the server about the book) and
Back to view to be displayed.
I started with getting the dropdown poplulated.
My View looks like this
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
My Controller:
public ActionResult Index()
{
ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
return View();
}
A dropdown list can't cause the page to post back to your controller on its own. You need to do one of two things:
Add a submit button so that the user changes the dropdown and then clicks a button to view the results.
Use javascript to submit the form on the element's change event.
Either way, you will need to wrap the dropdown/submit button in a form.
Option 1
<form>
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
<input type="submit" value="Show results" />
</form>
Option 2
<script type="text/javascript">
// assuming you're using jQuery
$(function() {
$('#UserSelectedValue').change(function() {
$(this).parent('form').submit();
});
});
</script>
<form>
BookName: #Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
<input type="submit" value="Show results" />
</form>
Your controller code would then become something like:
public ActionResult Index(string bookName)
{
ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
if (!string.IsNullOrWhiteSpace(bookName))
{
ViewData["Books"] = _context.BookName.Where(b => b.Book_Name == bookName).ToList();
}
return View();
}
Im making a form in ASP.Net MVC 3 C#.
This particular page of the form contains the user's employment history.
The user can have more than one employment history. So the view model contains a list.
Now it would be easy to so this (and it works):
int i = 0;
foreach (FrgCandidatePortal_2.Models.tblCandidateEmploymentHistory item in Model.empHistList)
{
<div>
<label>
Employment History #Html.Encode(i + 1)</label></h4>
<label>
Company Name</label>
<div>
#Html.EditorFor(c => c.empHistList[i].LJCOMP)
#Html.ValidationMessageFor(c => c.empHistList[i].LJCOMP)
</div>
...
</div>
i++;
}
BUT i want to be able to add an empty one using a button and ajax.
SO i figure "ill make it a partial view".
QUESTION 1: is a partial view the correct way to handle a recurring form element that needs add remove and save functionality?
Now I've made it a partial view and this is my view model for the page:
public class EmploymentHistoryViewModel : ViewModels
{
private List<EmploymentHistory_Partial> _EmploymentHistory_Partial_List;
public List<EmploymentHistory_Partial> EmploymentHistory_Partial_List
{
get
{
if (_EmploymentHistory_Partial_List.Count == 0)
{
int i = 0;
foreach (tblCandidateEmploymentHistory item in dataModel.candidateModel.tblEmpHistList)
{
_EmploymentHistory_Partial_List.Add(new EmploymentHistory_Partial(i, item));
i++;
}
return _EmploymentHistory_Partial_List;
}
else
{
return _EmploymentHistory_Partial_List;
}
}
set {
//foreach emphist partial fill emp hist
_EmploymentHistory_Partial_List.Clear();
dataModel.candidateModel.tblEmpHistList = value.Select(c=>c.empHist).ToList();
}
Basically my view model is a list of _EmploymentHistory_Partial's.
That displays data correctly when i use this code in my employment history view:
int i = 0;
foreach (FrgCandidatePortal_2.Models.EmploymentHistory_Partial item in Model.EmploymentHistory_Partial_List)
{
Html.RenderPartial("_EmploymentHistory_Partial",new FrgCandidatePortal_2.Models.EmploymentHistory_Partial(i,Model.EmploymentHistory_Partial_List[i].empHist));
}
BUT IT DOESNT SUBMIT
QUESTION 2: Why don't the values submit to the model on post?
(Im assuming its something to do with mvc naming conventions in the html document)
UPDATE
PROGRESS!
by editing the html of one of the fields (so that ID and NAME equaled EmploymentHistory_Partial_List[0].empHist.LJCOMP instead of empHist.LJCOMP) before i submitted when debugging. IT WORKED. It got to the set of EmploymentHistory_Partial_List in the view model.
So its naming. What seems to be happening is the partial view isn't inheriting the beginning of the naming from the rest of the form (and quite rightly). Is there any way to make that happen?
You can use EditorTemplates, either through an Html.BeginCollectionItem helper or just by calling Html.EditorFor(Model.EmploymentHistory_Partial_List).