Below Mention is the paging i have done using MVC PageList on my partial view and also i have one submit button on my partial view
Controller
var model1 = PrepareTestModel((int)_studAnsdal.Test_Id, Page);
ViewBag.TestId = TestId;
Page++;
return PartialView("_studentPartial", model1.OrderByDescending(v => v.Question_Id).ToPagedList(Page, 1));
View
<input type="submit" Value="Submit Answer" id="abc">
<div class="pagedList">
#Html.PagedListPager(Model, page => Url.Action("TestPaging", "Student", new { page=ViewBag.page, TestId = ViewBag.TestId }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions { UpdateTargetId = "results", HttpMethod = "POST" }))
</div>
What i want to do is whenver user click on submit i want to shift my paging value to the next page that is one increment to it but i m not getting it done as page value is passed using query string any help is appreciated
Related
I have ASPNETCore application with a model that successfully sends email and returns a message to the browser.
[HttpPost]
public IActionResult Index(IndexViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Send the email
_mailService.SendMessage(model.Email, model.Subject, $"From: {model.Name} - {model.Email}, Message: {model.Message}");
ViewBag.SendMessageClass = "p-3 mb-2 bg-success text-white rounded";
ViewBag.UserMessage = $"Nice to hear from you {model.Name}, your message was sent successfully";
ViewBag.JumpToDivId = "#contact_form";
ModelState.Clear();
}
catch (Exception ex)
{
ViewBag.SendMessageClass = "p-3 mb-2 bg-danger text-white rounded";
ViewBag.UserMessage = $"Whoops {model.Name}, we were unable to send the message, return code was {ex.ToString()}.";
ViewBag.JumpToDivId = "#contact_form";
}
}
return View();
}
After the post, I am trying to scroll back to near bottom of the page where the contact form is to show the message sent feedback. I have tried many examples and all just end up with the page at the top after postback not back to the contact form position. Any help appreciated.
Kind Regards,
Neil
trying to scroll back to near bottom of the page where the contact form is to show the message sent feedback
To achieve the requirement of maintaining the scroll position after the post, you can refer to the following approach to store the scroll position in localStorage while user submitting the form then retrieve it and dynamically reset the scroll position after page reloaded.
Html Code
<form>
input fields here
<br />
...
<br />
<input type="submit" value="Submit" onclick="maintainscrollposition()" />
</form>
JS Code
function maintainscrollposition() {
var y = window.scrollY
console.log(y);
localStorage.setItem('topposition', y);
}
$(function () {
var top = localStorage.getItem('topposition');
window.scroll(0, top);
localStorage.removeItem('topposition');
});
Test Result
I am working on an ASP.NET Core 2.1 MVC app using razor. I have searchQuery.cshtml and a (individually working perfectly) viewQuery.cshtml pages. In my searchQuery page, I let user enter queryId and on clicking "Search" button I want to run the action of ViewQuery that displays the results in viewQuery.cshtml and show the viewQuery below the search button area.
I am not good working with Ajax or so. On Search btn click, I call the viewQuery Get action thru ajax. In the button click, I pass the entered queryId of type int. But, when I load searchQuery page, it throws null exception for passing the queryId. I searched few hous, but didn't get any solution.
searchQuery.cshtml UPDATED
<div>
<div class="col-md-6">
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.QueryId)
</dt>
<dd>
<input asp-for="QueryId" class="form-control" />
</dd>
</dl>
</div>
<input type="submit" value="Show" />
<!-- CHANGE IN CALL -->
Search
</div>
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">Query Answer</h3>
</div>
<div class="modal-body" id="myModalBodyDiv">
</div>
<div class="modal-footer">
Ok
</div>
</div>
</div>
</div>
<script>
function ShowResult() {
// Retrieve queryId
var queryId = $("#QueryId").val();
// DisplayS PROPERLY
alert("Entered ID " + queryId);
// TRIED '/query/viewQuery' ALSO
$.ajax({
type: 'GET',
url: '../query/viewQuery',
data: { queryId: queryId },
success: function (response) {
alert(response); // **DISPLAYS [Object: object]**
$("#myModalBodyDiv").html(response);
$('#myModal').modal("show");
}, error: function (response) {
alert("Error: " + response);
}
});
}
</script>
My ViewQuery action in controller UPDATED
[Route("[controller]/viewQuery/{queryId:int}")]
public async Task<IActionResult> ViewQuery(int queryId)
{
// Retrieve Data from api using HttpClient
....
return PartialView("ViewQuery", qVM); // PartialView(qVM); //View(qVM);
}
Search Query Action UPDATED
[Route("searchQuery")] // customer/searchQuery
public IActionResult SearchQuery()
{
return View();
}
Can anyone please help me how do I achieve my goal. Simple - a text box were user enters queryId. A button on click, want to pass the entered queryId, call a GET action on controller and get the response. Finally show the response below the search button. I was just trying with the above modal dialog, I prefer text and not dialog.
Try & isolate the issue.
Instead of using model.QueryId in the searchQuery.cshtml, simply hardcode any reference to "modelid" - that way at least you are eliminating the possibility that Model is null on that page. Then instead of onclick="ShowResult(#Model.QueryId)"> , hard code some known id instead of #Model.QueryId. Then debug to see if your ViewQuery action method id hit. If the method is hit, then you can take it from there.
Also, I noticed that your jquery calls may need to be modified:
Instead of: $('myModalBodyDiv').html(response); it should probably be $('#myModalBodyDiv').html(response); (the "#" is missing ..) - same for $('myModal').
You can use Partial Pages(ViewQuery page) , in your searchQuery page , you could use Ajax to call server side action with parameter ID . On server side , you can query the database with ID and return PartialView with models :
[HttpPost]
public IActionResult Students (StudentFilter filters)
{
List students = Student.GetStudents(filters);
return PartialView("_Students", students);
}
Then in success callback function of Ajax , you can load the html of partial view to related area in page using jQuery :
success: function (result) {
$("#searchResultsGrid").html(result);
}
You can click here and here for code sample if using MVC template . And here is code sample if using Razor Pages .
I have problem with my ajax-search. When I adding to my model some data, I go to my Index view, where I use my ajax-search. And then I erase text from input and submit form, Index view did not show added data. How to fix that??
It's my SearchController
public ActionResult Index(string searhcString)
{
var competitions = from s in db.Competitions
select s;
if(!String.IsNullOrEmpty(searhcString))
{
competitions =competitions.Where(s => s.CompName.ToUpper().Contains(searhcString.ToUpper())
|| s.CompName.ToUpper().Contains(searhcString.ToUpper()));
}
return View(competitions);
}
Index View
#using (Ajax.BeginForm("AjaxSearch", "Competitions",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ajaxTable"
}))
{
<input type="text" name="q" />
<button type="submit"><img height="10" src="#Url.Content("~/Images/findBtn.png")" /></button>
}
In internet Explorer ajaxs calls are cached by default... may be this is your case.
You can disable this globally this way:
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
Or you can disable it just in this case adding cache: false in your AjaxOptions
Behind scene, this will append a timestamp to each call making it different from previous and that way preventing caching.
If this solves your issue, your could do something similar but sending a checksum of the value of your fields (instead of a timestamp)... this way, the post is only done when the filter/search options indeed changed.
I'm trying to do the same as this ASP.NET MVC Using two inputs with Html.BeginForm question describes but with enough difference that I don't really know hwo to apply it on my project:
I have a view that has 3 dropdownlists(profilelist, connected salarylist & not connected salarylist)
Looks like this:
<div class="row bgwhite">
#using (Html.BeginForm("GetConnectedSalaries", "KumaAdmin", FormMethod.Get, new { Id = "ProfileListForm" }))
{
<div class="four columns list list1">
#Html.DropDownList("Profiles", (SelectList) ViewBag.Profiles, "--Välj profilgrupp--",
new
{
//onchange = "$('#ProfileListForm')[0].submit();"
// Submits everytime a new element in the list is chosen
onchange = "document.getElementById('ProfileListForm').submit();"
})
</div>
}
#using (Html.BeginForm("Index", "KumaAdmin", FormMethod.Get, new { Id = "SalaryListForm" }))
{
<div class="four columns list list2" style="margin-top:-19px;">
#Html.DropDownList("Salaries", (SelectList) ViewBag.Salaries, "--Kopplade LöneGrupper--")
</div>
}
#using (Html.BeginForm("GetNOTConnectedSalaries", "KumaAdmin", FormMethod.Get, new { Id = "NotConSalaryListForm" }))
{
<div class="four columns list list2" style="margin-top:-19px;">
#Html.DropDownList("Salaries", (SelectList)ViewBag.NotConSalaries, "--Ej Kopplade LöneGrupper--")
<input style="float: left;" type="submit" value="Knyt" />
</div>
}
</div>
as you can see above when i change an element i the profile list i have script code that submits the form and calls the following actionresult that populates my "connected salarylist".
[HttpGet]
public ActionResult GetConnectedSalaries(int Profiles = -1)
{
Model.SalaryGroups = AdminManager.GetConnectedSalaries(Profiles);
ViewBag.Salaries = new SelectList(Model.SalaryGroups, "Id", "SalaryName", "Description");
return (Index());
}
What I wan't to do:
When I chose a element in the profilelist i would like to call 2 actionresults, the one that i have shown above AND a second one that will populare my third list that will contain "not connected salaries".
Second Actionresult:
public ActionResult GetNOTConnectedSalaries(int Profiles = -1)
{
Model.SalaryGroups = AdminManager.GetNOTConnectedSalaries(Profiles);
ViewBag.NotConSalaries = new SelectList(Model.NotConSalaryGroups, "Id", "SalaryName", "Description");
return (Index());
}
I don't want to do this with AJAX/JSON, strictly MVC.
I read the question that i linked above but did not know how to apply it to my project or if it is even possible to do the same.
If more info is needed ask and i will do my best to provide it.
Thank you!
I was so sure that the best way to do this was to have two actionresults that i was totaly blinded to the soloution that i could call both my db methods from the same actionresult and populate both of the lists.
Simple soloution:
[HttpGet]
public ActionResult GetSalaries(int Profiles = -1)
{
Model.SalaryGroups = AdminManager.GetConnectedSalaries(Profiles);
ViewBag.Salaries = new SelectList(Model.SalaryGroups, "Id", "SalaryName", "Description");
Model.NotConSalaryGroups = AdminManager.GetNOTConnectedSalaries(Profiles);
ViewBag.NotConSalaries = new SelectList(Model.NotConSalaryGroups, "Id", "SalaryName", "Description");
return (Index());
}
Sorry if I wasted your time:( but hopefully this will help others that attempt the same.
However if there is a way to do this in two actionresults then I will leave the question as open, would be interesting to see how it is done.
I use Dojo 1.3.1, essentially under FF3.5 for now.
I have a dnd source which is also a target. I programmatically add some nodes inside, by cloning template items. The aim for the user is then to use dnd to order the items. It is ok for one or two actions, then I got the "this.manager.nodes[i] is null" error in Firebug, then no more dnd action is taken into account.
My HTML (jsp), partial:
<div id="templates" style="display:none">
<div class="dojoDndItem action" id="${act.name}Template">
<fieldset>
<legend class="dojoDndHandle" >${act.name}</legend>
<input id="${act.name}.${parm.code}." type="text" style="${parm.style}"
dojoTypeMod="dijit.form.ValidationTextBox"
/><br>
</fieldset></div>
</div>
My Javascript for adding/removing dnd items nodes, partial :
function addActionFromTemplate(/* String */actionToCreate, /* Object */data) {
// value of actionToCreate is template id
var node = dojo.byId(actionToCreate + "Template");
if (node) {
var actNode = node.cloneNode(true);
// make template id unique
actNode.id = dojo.dnd.getUniqueId();
// rename inputs (add the action nb at the end of id)
// and position dojo type (avoid double parsing)
dojo.query("input[type=text], select", actNode).forEach( function(input) {
input.id = input.id + actionsCount;
dojo.attr(input, "name", input.id);
dojo.attr(input, "dojoType", dojo.attr(input, "dojoTypeMod"));
dojo.removeAttr(input, "dojoTypeMod");
});
// insert the action at script's tail
actionList.insertNodes(true, [ actNode ]);
dojo.parser.parse(actNode);
// prepare for next add
actionsCount++;
}
}
function deleteAction(node) {
var cont = getContainerClass(node, "action");
// remove the fieldset action
cont.parentNode.removeChild(cont);
}
Thanks for help ...
OK, it seems that, finally, simply using :
actionList.insertNodes(false, [ actNode ]);
instead of
actionList.insertNodes(true, [ actNode ]);
fixed the pb .