How to retain Select value after ajax within a partial view? - javascript

In my ASP.NET Core web application I have a partial view that will need to be placed in several views and be able to respond to dynamic data that will vary based on the view that's rendering this partial at the time. The red box in the image blow represents the area the partial is rendered.
The partial is essentially a Select that will call a Stored Procedure and return a datatable and render out the table to the partial view. I am able to select an option on the page and have it call the SP and see all relevant data from the datatable and can write that out on the page no problem. The problem I am having is that every time the partial refreshes via ajax, the Select returns to the default "Select" value and does not keep the previously selected option selected.
For the sake of brevity, assume that the FeedbackQueries object just contains 4 string elements.
_FeedbackQueryResultPartial.cshtml
#using Contract.Shared;
#model FeedbackQueries
<style>
#select {
margin: auto;
text-align: center;
}
</style>
<div id="feedbackQueryResultPartial">
<div style="height:25px;">
<div id="select">
<select name="StoredProcs" id="StoredProcs" onchange="selectQuery()">
<option value="Select">Select</option>
#foreach (FeedbackQuery query in Model.Queries)
{
#Html.Raw($"<option value='{query.SprocName}'>{query.SprocName}</option>");
}
</select>
</div>
<div id="feedbackQueryDiv" class="row">
#if (Model.FeedbackQueryResults.Rows.Count > 0)
{
<h3>DataTable goes here</h3>
}
else
{
<h3>No rows were returned from your query. Please select another.</h3>
}
</div>
</div>
</div>
Processing.cshtml
#using Contract.Parent
#using Contract.Shared
#model Processing
<script>
function showFeedbackPartial(x, y, z, q) {
$.ajax({
cache: false,
url: '#Url.Action("GetFeedbackQueryDatatable", "Client")',
type: 'POST',
data: { databaseConnectionString: x, storedProcedure: y, page: z, Model: q },
success: function (result) {
var selected = $('#StoredProcs').val();
console.log(selected);
if (result.rowCount > 0) {
console.log(result.rowCount);
var databaseConnectionString = x;
var storedProcedure = y;
var page = z;
var model = q;
var url = '#Url.Action("ViewFeedbackQueryPartial", "Client")';
$("#feedbackQueryResultPartial").load(url, { databaseConnectionString, storedProcedure, page, model });
}
else {
document.getElementById('feedbackQueryDiv').innerHTML = '<h3>No rows were returned from your query. Please select another.</h3>';
}
$('#StoredProcs').val(selected);
$("#StoredProcs option[value='Select']").remove();
}
});
}
</script>
<script>
function selectQuery() {
var e = document.getElementById('StoredProcs');
var ev = e.options[e.selectedIndex].text;
var p = 'Processing';
var model = #Html.Raw(Json.Serialize(Model.FeedbackQueries));
console.log(model);
showFeedbackPartial('#Model.Client.DatabaseConnectionString', ev, p, model);
}
</script>
<script>
$(document).ready(function () {
document.getElementById('feedbackQueryDiv').innerHTML = '<h3>Select a query to view feedback.</h3>';
});
</script>
}
<form method="post" enctype="multipart/form-data">
...
<partial name="_FeedbackQueryResultPartial" for="#Model.FeedbackQueries" />
...
</form>
Controller actions that render the Processing view
[HttpGet]
public IActionResult Processing(int Id)
{
ViewBag.Id = Id;
Processing processing = new Processing();
//Get pertinent information for Client
processing.Client = _clientProcessingService.GetSingleClient(Id, _appSettings.MOPConfigConnectionString);
processing.Client.DatabaseConnectionString = _clientProcessingService.GetClientConnectionFromConfig(processing.Client, _appSettings);
processing.Steps = _clientProcessingService.GetClientSteps(processing.Client.DatabaseConnectionString, "Processing");
processing.CurrMoInfo.CurrMo = _clientProcessingService.GetProcessingCurrMo(processing.Client.DatabaseConnectionString);
processing.FeedbackQueries = _clientProcessingService.GetFeedbackQueriesFromDb(processing.Client.DatabaseConnectionString, "Processing");
return View(processing);
}
[HttpPost]
public IActionResult Processing(Processing Model)
{
//Get pertinent information for Client
Model.Client = _clientProcessingService.GetSingleClient(Model.Client.ClientID, _appSettings.MOPConfigConnectionString);
Model.Client.DatabaseConnectionString = _clientProcessingService.GetClientConnectionFromConfig(Model.Client, _appSettings);
Model.Steps = _clientProcessingService.GetClientSteps(Model.Client.DatabaseConnectionString, "Processing");
Model.CurrMoInfo.CurrMo = _clientProcessingService.GetProcessingCurrMo(Model.Client.DatabaseConnectionString);
Model.FeedbackQueries = _clientProcessingService.GetFeedbackQueriesFromDb(Model.Client.DatabaseConnectionString, "Processing");
return View(Model);
}
Controller action that renders the partial
public IActionResult ViewFeedbackQueryPartial(string DatabaseConnectionString, string StoredProcedure, string Page, FeedbackQueries Model)
{
if(StoredProcedure == "Select")
{
return PartialView("_FeedbackQueryResultPartial", Model);
}
Model.FeedbackQueryResults = _clientProcessingService.GetFeedbackQueryDataTable(DatabaseConnectionString, Page, StoredProcedure);
return PartialView("_FeedbackQueryResultPartial", Model);
}
I have tried so many different ways of maintaining this value. Adding it to the model, adding it to the Viewbag and countless other methods of attempting to retain this value somewhere and regardless of success or failure, keep the value and change it to the selected option via javascript. It resets to "Select" every time the partial is reloaded after the ajax call is made.
This also presents another problem wherein, when I submit the form on the Processing view by clicking RUN the page will refresh and go to the next step in the process but ideally what should also happen is that the value in the partial is kept, the query is ran again and the user doesn't need to select a new value at any point unless they want to run a different SP to see different data in the table.
Is this even possible or am I trying to do this the entirely wrong way?

For your issue, you may need to pass the selected SprocName from Parent View to partial view with Model.
Add SelectedSprocName to FeedbackQueries
public class FeedbackQueries
{
public string SelectedSprocName { get; set; }
public List<FeedbackQuery> Queries { get; set; }
public FeedbackQueryResults FeedbackQueryResults { get; set; }
}
Change View to set SelectedSprocName
function showFeedbackPartial(x, y, z, q) {
$.ajax({
cache: false,
url: '#Url.Action("GetFeedbackQueryDatatable", "Process")',
type: 'POST',
success: function (result) {
var selected = $('#StoredProcs').val();
model.SelectedSprocName = selected;
var url = '#Url.Action("ViewFeedbackQueryPartial", "Process")';
$("#feedbackQueryResultPartial").load(url,{ databaseConnectionString, storedProcedure, page, model });
console.log('after load' + selected);
// your rest code
}
});
}
Partial View set selected option
#foreach (FeedbackQuery query in Model.Queries)
{
if (query.SprocName == Model.SelectedSprocName)
{
#Html.Raw($"<option value='{query.SprocName}' selected='true'>{query.SprocName}</option>");
}
else
{
#Html.Raw($"<option value='{query.SprocName}'>{query.SprocName}</option>");
}
}

Related

How do I retrieve a viewmodel from another viewmodel?

I have this ViewModel which incorporates 3 other viewmodels and a list:
public class GroupPageViewModel{
public string GroupName { get; set; }
public GroupSelectViewModel _groupSelectVM {get; set;}
public List<User> _users { get; set; }
public ViewModelStudent _studentVM { get; set; }
public ViewModelGroupMembers _groupMembersVM { get; set; }
}
In the view I can access each of these sub-ViewModels by Model._groupSelectVM, each of the sub-ViewModels are associated with a partial view. The problem arises when I need to refresh just one or two partial views, I'm not sure how to access the inner ViewModels returned in an Ajax success, and as I'm relatively new to MVC and asp.net in general. And I literally know next to nothing about JavaScript, jquery or Ajax.
How would I go about getting a specific ViewModel from the main ViewModel in an Ajax success?
This is just one example for the clarification requested all the others are pretty much the same (although some of them might need to update mutliple partial views -
From the controller:
[HttpPost]
public ActionResult Index(string groupChoice = "0", string newGroup = "")
{
string groupName = "";
if (groupChoice == "0" && newGroup != "")
{
if (ModelState.IsValid)
{
Group group = new Group
{
GroupName = newGroup,
Active = true
};
db.Groups.Add(group);
db.SaveChanges();
PopulateLists();
}
}
else if (groupList == null)
{
groupList = (List<SelectListItem>)Session["groupList"];
Session["groupName"] = groupName = groupList.Where(m => m.Value == groupChoice).FirstOrDefault().Text;
MembersInSpecificGroup(groupName, groupMembers, groupMembersList);
groupPageVM._groupMembersVM = groupMembers;
}
return View("GroupSelection", groupPageVM);
}
The script:
$(document).ready(function () {
$('#selectedGroup').change(function () {
var data = {
groupChoice: $('#selectedGroup').val()
};
var groupChoice = $('#selectedGroup').val();
$.ajax({
url: '/Group/Index/',
type: 'POST',
data: { groupChoice: groupChoice },
success: function (data) {
setTimeout(function () {
delayGroupSuccess(data);
}, delay);
}
});
})
});
function delayGroupSuccess(data) {
$("#groupSelect").html(data);
}
The main page:
#model EMBAProgram.ViewModels.GroupPageViewModel
#{ Layout = "~/Views/Shared/_Layout.cshtml"; }
<h2>Group Selection</h2>
<div class="row" id="groupSelect">
#{ Html.RenderPartial("_GroupSelect", Model._groupSelectVM);}
</div>
<hr size="5" />
<div style="display: flex;">
<div>
#{Html.RenderPartial("_Students", Model._studentVM);}
</div>
<div>
#{ Html.RenderPartial("_GroupMembers", Model._groupMembersVM);}
</div>
<div>
#{ Html.RenderPartial("_Users", Model._users);}
</div>
<br style="clear: left;" />
</div>
The partial view:
#model EMBAProgram.ViewModels.ViewModelGroupMembers
<div class="table-responsive" id="groupResults">
<table class="table table-condensed table-responsive">
<thead>
<tr>
<th>#Html.DisplayName("M-Number")</th>
<th>#Html.DisplayName("Name")</th>
<th>#Html.DisplayName("Student")</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model._groupVM) {
<tr>
<td>#Html.DisplayFor(m => item.MNumber)</td>
<td>#Html.DisplayFor(m => item.Name)</td>
<td>#Html.DisplayFor(m => item.Student)</td>
</tr>
}
</tbody>
</table>
</div>
Basically I need to be able pull the ViewModel for the partial view from the main ViewModel (which I believe is what is being returned in the Ajax,) and refresh the partial view.
I removed the original answer, it's available in the edit log if folks want to see it I think. But it was taking up too much space and was incorrect.
You can return multiple partial views, I thought it was a built in way to get them to a string (I was in a rush in my comment), but I've got a working example.
In the controller I have the following:
public ActionResult Index()
{
var model = new TestViewModel
{
Students = GetStudents(),
Categories = GetCategories(),
Groups = GetGroups()
};
return View("Index", model);
}
// Returns multiple partial views as strings.
public ActionResult StudentsAndGroups()
{
return Json(new
{
Students = RenderRazorViewToString("_Students", GetStudents()),
Groups = RenderRazorViewToString("_Groups", GetGroups())
}, JsonRequestBehavior.AllowGet);
}
// Creates a string from a Partial View render.
private string RenderRazorViewToString(string viewName, object model)
{
ControllerContext.Controller.ViewData.Model = model;
using (var stringWriter = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return stringWriter.GetStringBuilder().ToString();
}
}
I have my main index view that looks like the following:
<button class="refresh">Refresh</button>
<div class="row">
<div class="col-md-4 students">
#{
Html.RenderPartial("_Students", Model.Students);
}
</div>
<div class="col-md-4">
#{
Html.RenderPartial("_Category", Model.Categories);
}
</div>
<div class="col-md-4 groups">
#{
Html.RenderPartial("_Groups", Model.Groups);
}
</div>
</div>
#section scripts
{
<script type="text/javascript">
$(".refresh").click(function () {
$.get("/Home/StudentsAndGroups", function (d) {
$(".students").html(d.Students);
$(".groups").html(d.Groups);
})
});
</script>
}
The controller action StudentsAndGroups turns two partial views into strings. From there, the javascript calls that view and accesses the elements and returns them.
Helper method for rendering a view as a string was found here: https://stackoverflow.com/a/34968687/6509508

asp.net - Manipulate Page Content

I was wondering if anyone could explain how to manipulate content for various sections of a page depending on if a button is clicked. I think what I am looking for is similar to an include in php. I wasnt sure if asp.net had a way to do the same (partial view?) or if bootstrap/jquery is the way to go. I've included a .png to illustrate what I am trying to do.
I would like section b's content to change based on what button is selected in section A. While not necessarily relevant to this question.. I then would like various user inputs in section B to manipulate existing content in section C.
In your controller, have an action that returns a PartialView:
public PartialViewResult MyPartial(string someText)
{
var model = new MyPartialModel {SomeStuff = someText};
return PartialView(model);
}
Create the model and partial view as you would any other:
public class MyPartialModel
{
public string SomeStuff { get; set; }
}
Partial View:
#model ExampleApp.Models.MyPartialModel
#Html.TextBoxFor(m => m.SomeStuff)
Then on your page you can load in your partial via ajax with jQuery:
<div>
<button type="button" id="load-partial">Load The Partial!</button>
</div>
<div id="section-b"></div>
#section Scripts{
<script>
$(document).ready(function () {
$('#load-partial').click(function () {
$.get('MyPartial', { sometext: "Hello!" }).done(function (data) {
$('#section-b').html(data);
});
});
});
</script>
}
Edit to answer comment:
If you don't want to instantiate a new model in the controller each time, you can pass the model (more or less) directly from the view.
In you controller, have a very simple action that accepts a model as a parameter and returns the partial view. Note the HttpPost attribute.
[HttpPost]
public PartialViewResult MyPartial(MyPartialModel model)
{
return PartialView(model);
}
The model's got more than one property this time:
public class MyPartialModel
{
public string Name { get; set; }
public int Age { get; set; }
}
The partial's pretty much the same, except it now displays the new properties of the model.
#model MVCPlayGround.Models.MyPartialModel
#Html.TextBoxFor(m => m.Name)
#Html.TextBoxFor(m => m.Age)
The jquery on the main page/view is very also similar, but uses POST instead of GET.
// these could be anything, from control on the page, or whatever
var name = "James";
var age = 30;
$(document).ready(function () {
$('#load-partial').click(function () {
// note that Name and the Age are the names of the properties in our model
$.post('MyPartial', { Name: name, Age: age }).done(function (data) {
$('#section-b').html(data);
});
});
});
This works because when data transmitted via POST, it's treated as form data, and when the controller's deciding which action to use it'll look at the parameters for the actions, and compare them to the form data available. The MyPartialModel contains properties that match the form data, so it chooses that action. There are other subtle rules, but that's basically it. Behind the scenes it'll still be instantiating a model in the controller, it's just in the framework, not in the code you've written.
Another edit
Having just re-read your comment I don't think I've answered it fully.
If you want to save the changes you've made in a partial view to the main view, have some hidden fields in the main view to hold this data.
<input type="hidden" id="name-holder" />
<input type="hidden" id="age-holder" />
And then when you want to store a value to them, just set the values with jquery:
$('#some-save-button-maybe').click(function(){
$('#name-holder').val($('id-of-name-on-partial').val());
$('#age-holder').val($('id-of-age-on-partial').val());
});
When you click on a the button to show a partial, send the appropriate data to the controller to render in the partial:
$('#load-partial').click(function () {
$.post('MyPartial', { Name: $('#name-holder').val(), Age: $('#age-holder').val() }).done(function (data) {
$('#section-b').html(data);
});
});
Hopefully that's what you need...
Yes there are partial views in MVC, and they are usually belong in the Views/Shared folder of your project and are prefixed with a _ (i.e. _MyPartial.cshtml.
As #AdamHeeg pointed out in the comments, there are many tutorials on the web about this kind of setup and many different ways to achieve what you are after.
Here is roughly how I might tackle it...
HTML
<nav>
#Html.ActionLink("Button 1", "GetSectionB")
</nav>
<section id="sectionB">
<!-- Content here -->
</section>
JavaScript
$('nav a').on('click', function (e) {
e.preventDefault();
$.get(this.href, function (html) {
$('#sectionB').html(html);
});
});
Controller
public PartialViewResult GetSectionB()
{
var vm = new MyViewModel();
//do stuff
return PartialView("_SectionB", vm);
}

How do I dynamically update a div instantly when an item in a dropdownlist is selected?

Edit for clarity: When an item in the dropdownlist is selected, call a method in my controller which will return a partialview and update a div on my page.
I have a ActionLink PartialView which I want to be called every time I select a new item in the dropdown list to update a table I have on my webpage - how do I make this happen without needing to press a button?
#Html.DropDownListFor(m => m.SelectedCustomerId, Model.CustomerIDItem)
I can do a Request["selectedCustomerId"] to retrieve the value from it without any problems but my question really is about the dynamic part. The first idea was to connect AJAX to the dropdownlist or using JQuery but I have no idea how to actually make this work.
Thanks in advance.
Edit 4:
Adding all of my code:
_DefaultValuesView.cshtml:
#Html.DropDownListFor(m => m.SelectedCustomerId, Model.CustomerIDItem)
<div id="divValues">
#{ Html.RenderPartial("_DefaultValuesPartialView");}
</div>
DefaultValuesController.cs
[HttpPost]
public PartialViewResult DefaultValuesPartialView(string SelectedCustomerId)
{
Session["theCustomerId"] = Request["selectedCustomerId"];
var model = new DefaultValuesModel
{
CustomerIDItem = GetCustomerIds(),
FieldIDItem = GetValues(),
CurrentValuesItem = GetCurrentValues()
};
model.TriggerOnLoad = true;
this.customerId = Convert.ToInt32(Request["selectedCustomerId"]);
errorMessage = "PartialView is loaded!";
model.TriggerOnLoadMessage = errorMessage;
return PartialView("_DefaultValuesPartialView", model);
}
I would do it like this:
#Html.DropDownListFor(m => m.SelectedCustomerId, Model.CustomerIDItem, new { #id = "customId" })
<div id="divValues">
</div>
$(function() {
$("#customId").change(function() {
var id = $(this).val();
$('#divValues').load('#Url.Action("DefaultValuesPartialView", "DefaultValues")?selectedCustomerId=' + id, function (response, status, xhr) {
$("#divValues").html(response);
});
});
});
Your controller Action then looks like this:
public PartialViewResult DefaultValuesPartialView(int? selectedCustomerId)
{
Session["theCustomerId"] = selectedCustomerId.Value;
var model = new DefaultValuesModel
{
CustomerIDItem = GetCustomerIds(),
FieldIDItem = GetValues(),
CurrentValuesItem = GetCurrentValues()
};
model.TriggerOnLoad = true;
this.customerId = selectedCustomerId.Value;
errorMessage = "PartialView is loaded!";
model.TriggerOnLoadMessage = errorMessage;
return PartialView("_DefaultValuesPartialView", model);
}
Please consider that your Partial views name needs to bee the same as your controller action name.
You load your data with the jQuery function .load this is a common way and I use everytime if I need to do something like you want to do
If I understood you correctly this should do it (it uses JQuery)... JSFiddle here
<select id="myDdl">
<option value="AM">AM</option>
<option value="PM">PM</option>
</select>
<div id="babylonAndTing">
A up lad.
</div>
$(function() {
$("#myDdl").change(function() {
$("#babylonAndTing").text( $('option:selected', this).text() );
});
});
P.S. Hmm on second thoughts, I answered your question title 'How do I dynamically update a div instantly when an item in a dropdownlist is selected?', but your question text is asking something different?!?!? Ah well I'll leave this answer for the people who read your title and come here :p
Edit:
As for your question in the text, try something like this...
#using (Ajax.BeginForm("SelectCustomer", "MyControllerName", FormMethod.Post, null))
{
#Html.DropDownListFor(m => m.SelectedCustomerId, Model.CustomerIDItem)
}
<script type="text/javascript">
$('#SelectedCustomerId').change(function () {
$(this).parents('form').submit();
});
</script>
[HttpPost]
public ActionResult SelectCustomer(int? selectedCustomerId)
{
// Stuff goes here.
}
You can make an ajax request to the partial view and get back just the HTML content of it. The key is using url: "#Url.Action("DefaultValuesPartialLayout")" to get the right URL to load your partial from.
<div id="divValues">
#{ Html.RenderPartial("_DefaultValuesPartialLayout");}
</div>
$(document).ready(function() {
$("##Html.IdFor(m => m.SelectedCustomerId)").change(function() {
var selectedCustomerId = $("##Html.IdFor(m => m.SelectedCustomerId)").val();
$.ajax({
url: "#Url.Action("DefaultValuesPartialView")",
method: "GET",
data: { SelectedCustomerId: selectedCustomerId },
success: function(data, status, xhr) {
$("#divValues").html(data);
}
});
})
});

In an MVC project, how do you update the model when a drop down list changes value?

I have a MVC project using Kendo controls. On one of the views is a drop down box and text box. Both are initially getting their values from the model. How can I change the model (and therefore the text box) when the user selects an item from the drop down?
For example, the Model is filled in the controller setting the original value of the item the drop down box is based on to "General" and the item the text box is based on to "Widgets". When the user selects "Special" from the drop down, the controller would query the database to get data based on "Special", find that the new value of the text box should say "Doodads", add "Doodads to the model and change the text box to "Doodads".
View
#model GPC.Models.ModelInstrumentListingDetail
#using (Html.BeginForm("InstrumentListingDetailClick", "Home", FormMethod.Post, new { id = "InstrumentListingDetailForm" }))
{
<div id="divInstrumentListingDetailHeader" class="detailDivs">
<table>
<tr>
<tr>
<td style="text-align: right;" class="dropdowns">
<label>Category:</label>
</td>
</tr>
</table>
</div> // divInstrumentListingDetailHeader
<div id="divInstrumentListingDetailBody" class="detailDivs details">
<table class="details">
#*Field 1*#
<tr>
<td style="text-align: right;">
#Html.DisplayFor(m => m.Label1)
</td>
<td width="2px;"> </td>
<td class="dropdowns">
#Html.TextBoxFor(m => m.Field1, new { #class = "details" })
</td>
</tr>
</table>
</div> // divInstrumentListingDetailBody
}
<script>
function onChange_ddInstrumentCategory(arg) {
var categoryID = $(arg).find('option:selected').val();
// Update model based on the category ID
}
</script>
Controller
public ActionResult InstrumentListingEdit(TblInstrumentTag model)
{
TblInstrumentTag currentInstrumentTag = data.GetInstrumentTagByID(model.InstrumentTagID);
// Fill Category drop down
List<TblInstrumentFormCategory> categories = data.GetAllCategories();
// Create model
ModelInstrumentListingDetail detailModel = new ModelInstrumentListingDetail
{
InstrumentTagID = currentInstrumentTag.InstrumentTagID,
InstrumentCategory = categories.FirstOrDefault().InstrumentFormCategoryID,
Field1 = currentInstrumentTag.FormCategory1Value1,
Label1 = categories.FirstOrDefault().Label1 + ":",
ieInstrumentCategories = new SelectList(categories, "InstrumentFormCategoryID", "InstrumentFormCategoryName")
};
return View("InstrumentListingEdit", detailModel);
}
Model
public class ModelInstrumentListingDetail
{
// Drop down ID's
public int InstrumentTagID { get; set; }
public int InstrumentCategory { get; set; }
// Detail fields
public string Field1 { get; set; }
// Detail labels
public string Label1 { get; set; }
// Drop downs for add/edit page
public IEnumerable<SelectListItem> ieInstrumentCategories { get; set; }
}
What I'd like is to get from the javascript to something like this code below to update the text box. I'd rather not post the entire page. I don't want the screen to "blink"; I just want the user to select an item from the dropdown and for the textbox value to change.
Need to get from jQuery to something like this without submitting the form:
public ActionResult UpdateModel(TblInstrumentTag model, int newCatgoryID)
{
TblInstrumentTag currentInstrumentTag = data.GetInstrumentTagByID(model.InstrumentTagID);
// Fill Category drop down
List<TblInstrumentFormCategory> categories = data.GetAllCategories();
// Create model
ModelInstrumentListingDetail detailModel = new ModelInstrumentListingDetail
{
InstrumentTagID = currentInstrumentTag.InstrumentTagID,
InstrumentCategory = categories.FirstOrDefault().InstrumentFormCategoryID,
Field1 = currentInstrumentTag.FormCategory2Value1, // <- Value of Field 1 has changed
Label1 = categories.FirstOrDefault().Label1 + ":",
ieInstrumentCategories = new SelectList(categories, "InstrumentFormCategoryID", "InstrumentFormCategoryName")
};
return View("InstrumentListingEdit", detailModel);
}
JQuery is a good place to start. If I understand correctly, you only want to query the DB after changing the drop down's value, and then changing the value of the textbox to the corresponding change.
JQuery:
$(document).ready(function(){
$('#myDropDown').change(selectionChange());
});
function selectionChange() {
var dropDownValue = $('#myDropDown').val();
var textBox = $('#myTextBox');
$.ajax({
url: "/mycontroller/querydb",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(dropDownValue),
success: function (data, status) {
textBox.val(data);
},
type: "post"
});
return;
}
Controller:
[HttpPost]
public JsonResult QueryDB(string dropDownValue)
{
string newTextBoxValue = string.Empty;
//your db code
return Json (newTextBoxValue) );
}
It's a fairly watered down version of a JQuery AJAX to MVC Controller deal. Hopefully it will work for you!

Webgrid refresh with ajax in MVC3

I have a Webgrid that I need to refresh when pressing a button 'Refresh'. I also have a search input.
Everything is working fine, except that everytime that I hit refresh, the pageNumber is being set back to one...
Here is my code...
controller
public ActionResult ListImporting(string searchText = "", int page = 1)
{
ViewBag.RowsPerPage = 2;
searchText = searchText.Trim();
ViewBag.searchText = searchText;
ViewBag.page = page;
DtoPaginatedResult<ListImportingDTO> model = listService.GetListsInProgress(page, ViewBag.RowsPerPage, searchText);
if (Request.IsAjaxRequest())
return PartialView("ListImportingGrid", model);
else
return View(model);
}
Then I have a view List Importing that calls the partial...
<input id="refreshButton" type="button" value="Refresh" style="float:right"/>
<div id="resultList" style="margin-top:20px">
#Html.Partial("ListImportingGrid", Model)
</div>
......
$("#refreshButton").live("click",updateGrid);
And inside the partial I have the grid, and the current function
function updateGrid() {
var pageNumber = #ViewBag.page;
console.log(pageNumber);
$.ajax(
{ type: "GET" ,
url: '/Admin/ListImporting/',
data: { searchText: $("#searchBox").val(),
page: pageNumber
} ,
dataType: "html" ,
success: function (data){
$("#resultList").html(data);
}
})
}
When the page is loaded you are hard coding the pagenumber to ViewBag.page which is always going to be equal to one on page load.
Instead what you need to do is create a hidden input in the partialview and place the javascript code in the main view.
Then when the updateGrid function is triggered look in the patial view, via javascript, and find the value that is in the hidden field for the page number.
Switch to PagedList, it's a lot easier to work with ajax, pagination, and webgrids.
https://github.com/TroyGoode/PagedList
Your pageNumber is being reset back to 1 because every time you call updateGrid you're resetting it to the ViewBag.page
in other words, the compiled razor code looks like
function updateGrid() {
var pageNumber = 1;
....
So you should create pageNumber somewhere else, if you don't want it to be reset when you call updateGrid, like this
var pageNumber = ViewBag.page;
function updateGrid() {
....

Categories

Resources