I have an main overview.cshtml page that has the following code to run a partial:
<div>
Html.RenderAction("UserProjMetric", "Users", new {id = Model.Id});
</div>
Inside of that partial it looks like so:
#model RecruiterMetricsViewModel
<div>
<div>
<input type="text" id="dates start" />
<input type="text" id="dates end" />
<input type="submit" onclick="runAjax()" />
<table>
#foreach(var data in Model.Metrics)
{
<tr> <td>#data</td> </tr>
}
</table>
</div>
I want to make the onclick run some ajax that will reload the entire partial. The user has the ability to specify a date range. When they do that then click submit I want the entire partial to be reloaded.
How do I do that and is that possible?
This should do what you want. A bit more verbose than Jonesy's comment, perhaps they would accomplish the same thing. You could try replacing Html.BeginForm with Ajax.BeginForm I suppose.
// overview.cshtml
<div id="UserProjWrapper">
Html.RenderAction("UserProjMetric", "Users", new {id = Model.Id});
</div>
// UserProjMetric.cshtml
#model RecruiterMetricsViewModel
#using(Html.BeginForm("UserProjMetric","Users",null,FormMethod.Post, new {id = "UserProjForm" }))
{
<input type="text" name="startDate" class="dates start" />
<input type="text" name="endDate" class="dates end" />
<input type="submit" value="Submit"/>
<table>
#foreach(var data in Model.Metrics)
{
<tr> <td>#data</td> </tr>
}
</table>
}
<script>
$(function() {
$('#UserProjForm').submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"),$(this).serialize(),function(response) {
$('#UserProjWrapper').html(response);
});
});
});
</script>
Related
I am trying to make it possible for a user to accept/reject an item stating a reason in any of the items presented in a table with a PaginatedList:
#model PaginatedList<ItemViewModel>
<table>
<thead>
...
</thead>
for (int i = 0; i < Model.Count(); i++){
var item = Model.ElementAt(i);
...
<tr>
<td><input asp-for="#item.AdditionalText" type="text" /></td>
<td>
<form asp-action="AddAdditionalText" method="post" asp-route-trackID="#item.itemID" asp-route-notes="#item.AdditionalText">
<input value="Accept Item" type="submit" class="btn btn-success btn-lg">
</form>
</td>
<td>
<form asp-action="AddAdditionalText" method="post" asp-route-trackID="#item.itemID" asp-route-notes="#item.AdditionalText">
<input value="Reject Item" type="submit" class="btn btn-success btn-lg">
</form>
</td>
<tr>
...
Data is submitted to the controller and in the action, I see only the itemID being submitted and not the notes. It is null because it is out of form. I tried but it doesn't work. Could you please suggest a solution?
You should include the notes in the form which is being submitted. Keep the input element for the AdditionalText in the same form where you submit buttons are. Also keep a name attribute on your submit buttons so that you know which button is clicked, inside your http post action method
<form asp-action="AddAdditionalText" method="post" asp-route-trackID="#item.itemID">
<input asp-for="#item.AdditionalText" type="text" />
<input value="Accept Item" name="reason" type="submit" class="btn">
<input value="Reject Item" name="reason" type="submit" class="btn">
</form>
and in the action method.
public ActionResult AddAdditionalText(int trackId,string AdditionalText, string reason)
{
if (reason == "Accept Item")
{
}
else
{
}
// to do : return something
}
I have table and <tbody> of this table is getting filled from the list in the model.
The list has id for each item which is getting assigned to data-id in anchor tag
<tbody>
#foreach (var item in Model.eList.ToList())
{
<tr>
<td>#item.FullName</td>
<td>#item.Title</td>
<td><a data-id="#item.Id" data-open="Event">Event</a></td>
</tr>
}
</tbody>
I have div with Id Event like this
<div id="Event" class="reveal" data-reveal>
#using (Html.BeginForm("Cancel", "Profile", new { id = data-id}, FormMethod.Post))
{
<label>confirm</label>
<input type="submit" value="Save" class="button" id="Edits" />
}
</div>
When user clicks on anchor tag it will open the div with id="Event". But how do I pass data-id for that particular record to div with id="Event", from there it will be posted to controller with action cancel.
Thank you
You can keep a hidden input element inside that form.
<div id="Event" class="reveal" data-reveal>
#using (Html.BeginForm("Cancel", "Profile"))
{
<input id="dataId" name="id" value="" type="hidden" />
<label>confirm</label>
<input type="submit" value="Save" class="button" id="Edits" />
}
</div>
and when user clicks the anchor tag, read the value from the data-id attribute of the clicked element and set it as the value of the hidden element.
$(function(){
$("[data-id]").click(function(e){
e.preventDefault();
var id=$(this).data("id");
$("#dataId").val(id);
// your existing code to open the div with form
/ /$("#Event").show();
});
});
When the user submits the form, the id value we set to the hidden input will also be submitted.
Here is a js bin sample.
You can post Id in either -
Query String as new {id = item }, or
Hidden Field as <input type="hidden" name="id" value="#item">
For example,
<tbody>
#foreach (var item in Model.eList.ToList())
{
<tr>
<td>#item.FullName</td>
<td>#item.Title</td>
<td>
#using (Html.BeginForm("Cancel", "Profile", new {id = item },
FormMethod.Post))
{
<a data-id="#item.Id" data-open="Event">Event</a>
<input type="hidden" name="id" value="#item">
<div id="Event" class="reveal" data-reveal>
<label>confirm</label>
<input type="submit" value="Save" class="button" id="Edits" />
</div>
}
</td>
</tr>
}
</tbody>
I have a question concerning updating a partial view from another partial view where the first view is contained.
I have 4 dropdowns that are populated based on the previous selections, then the user may submit their selections and a database is queried and a table is populated based on their selections. I should note that I am very new to asp.net mvc and it's all still quite confusing to me.
Below is my code:
<form action="/Home/LoadRelease" method="post" style="text-align: center;">
#*Headers*#
<div id="BusinessAreaLabel" class="inline" style="width:14em;">Business Area</div>
<div id="GenericProjectLabel" class="inline" style="width:13em;">Generic Project</div>
<div id="ProjectLabel" class="inline" style="width:17em;">Project</div>
<div id="ReleaseLabel" class="inline" style="width:13em;">Release</div>
<br />
#*Dropdowns*#
<select id="BusinessAreaDropDown" name="BusinessArea" onchange="javascript: FillGenericProject(); FillProject(); FillReleases();" style="width: 13em;">
#Html.Partial(#"Dropdowns\_BusinessArea", Model.ProjectViewModels);
</select>
<select id="GenericProjectDropDown" name="GenericProject" onchange="javascript: FillProject(); FillReleases();" style="width: 13em;"></select>
<select id="ProjectDropDown" name="Project" style="width: 17em;" onchange="javascript: FillReleases();"></select>
<select id="ReleaseDropDown" name="Release" style="width: 13em;"></select>
<input type="submit" id="GoButton" style="visibility:hidden;" value="Go" />
</form>
<form id="ReleaseTableBody" style="text-align:center;">
#Html.Partial("_TableBody", Model.OpenCloseViewModels) //I want to update this.
</form>
<br />
and Home/LoadRelease:
[HttpPost]
public ActionResult LoadRelease(string Project, string Release)
{
var ProjectID = _ProblemReportsDB.ProjectMaps
.Where(r => r.Project == Project)
.Select(r => r.ID).FirstOrDefault();
ViewBag.Project = Project;
var Releases = from row in _ProblemReportsDB.PlannedOpenCloses
where (row.Project == ProjectID)
select row;
return PartialView("_TableBody", Releases.ToList());
}
The above loads the partial view "_TableBody", but actually directs to the page containing only the contents of _TableBody.
Ideally, I would remain on the page displaying and only update the _TableBody section of the page. I think I understand why it is currently failing, I'm telling it to run the action /Home/LoadRelease, which returns the _TableBody partial view, which it loads.
I'm having trouble figuring out how to make it only update the _TableBody partial view.
Thanks for any help you can offer.
EDIT:
Attempting Jasens method I have begun using an ajax function: Still loads to another page instead of updating the partial:
Code:
#using (Html.BeginForm("LoadRelease", "Home", FormMethod.Post, new { id = "DropDownForm", style="" }))
{
#*Headers*#
<div id="BusinessAreaLabel" class="inline" style="width:14em;">Business Area</div>
<div id="GenericProjectLabel" class="inline" style="width:13em;">Generic Project</div>
<div id="ProjectLabel" class="inline" style="width:17em;">Project</div>
<div id="ReleaseLabel" class="inline" style="width:13em;">Release</div>
<br />
#*Dropdowns*#
<select id="BusinessAreaDropDown" name="BusinessArea" onchange="javascript: FillGenericProject(); FillProject(); FillReleases();" style="width: 13em;">
#Html.Partial(#"Dropdowns\_BusinessArea", Model.ProjectViewModels);
</select>
<select id="GenericProjectDropDown" name="GenericProject" onchange="javascript: FillProject(); FillReleases();" style="width: 13em;"></select>
<select id="ProjectDropDown" name="Project" style="width: 17em;" onchange="javascript: FillReleases();"></select>
<select id="ReleaseDropDown" name="Release" style="width: 13em;"></select>
<button type="submit" id="GoButton" style="visibility:hidden;">Go</button>
}
#*</form>*#
<form id="ReleaseTableBody" style="text-align:center;">
#Html.Partial("_TableBody", Model.OpenCloseViewModels)
</form>
<br />
In index: (Parent of _DropDownBody):
<script src="~/Scripts/jquery-1.10.2.js">
$(document).ready(function () {
$("#DropDownForm").on("submit", function (event) {
event.preventDefault();
var form = $(this);
var Project = $('#ProjectDropDown').val();
var Release = $('#ReleaseDropDown').val();
alert(Project);
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: form.serialize()
})
.done(function (result) {
$("#ReleaseTableBody").html(result);
});
});
});
</script>
Using A. Burak Erbora's method produces the same issue as well. Am I missing something?
Final edit: Jasen's answer worked and allowed me to update a partial view without redirecting. Still having issues getting the partial to show my content, but as far as the question goes - Jasen's answer works!
Submitting a form will cause navigation. Since you want to stay on the same page you'll need to trap the submission event and use AJAX to update your page.
Main View
#using(Html.BeginForm("LoadRelease", "Home", FormMethod.Post, new { id = "DropDownForm", style = "" })
{
<!-- your drop down inputs -->
<button type="submit">Go</button>
}
<form id="ReleaseTableBody" style="text-align:center;">
#Html.Partial("_TableBody", Model.OpenCloseViewModels) //I want to update this.
</form>
Then the page script (don't forget to load jquery.js before this). Also note if you are embedding partial views you need to move this script "up" to the parent since #section will not render in partials.
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#DropDownForm").on("submit", function(e) {
// prevent default submission
e.preventDefault();
// do AJAX post instead
var form = $(this);
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: form.serialize()
})
.done(function(result) {
// replace content
$("#ReleaseTableBody").html(result);
});
});
}
</script>
Controller action unchanged
[HttpPost]
public ActionResult LoadRelease(string Project, string Release)
{
// search
return PartialView("_TableBody", results);
}
First off, I'd recommend you use html helpers. What you seem to need here is an ajax call instead of a standard form post. Instead of
<form action="/Home/LoadRelease" method="post" style="text-align: center;">
you can use
#using (Ajax.BeginForm("LoadRelease", "Home", options)){
#*Headers*#
<div id="BusinessAreaLabel" class="inline" style="width:14em;">Business Area</div>
<div id="GenericProjectLabel" class="inline" style="width:13em;">Generic Project</div>
<div id="ProjectLabel" class="inline" style="width:17em;">Project</div>
<div id="ReleaseLabel" class="inline" style="width:13em;">Release</div>
<br />
#*Dropdowns*#
<select id="BusinessAreaDropDown" name="BusinessArea" onchange="javascript: FillGenericProject(); FillProject(); FillReleases();" style="width: 13em;">
#Html.Partial(#"Dropdowns\_BusinessArea", Model.ProjectViewModels);
</select>
<select id="GenericProjectDropDown" name="GenericProject" onchange="javascript: FillProject(); FillReleases();" style="width: 13em;"></select>
<select id="ProjectDropDown" name="Project" style="width: 17em;" onchange="javascript: FillReleases();"></select>
<select id="ReleaseDropDown" name="Release" style="width: 13em;"></select>
<input type="submit" id="GoButton" style="visibility:hidden;" value="Go" />
}
and somewhere in your html you have:
<div id="ReleaseTableBody">
#Html.Partial(_TableBody", Model.OpenCloseViewModels)
</div>
you will need to define the options object for the Ajax helper like:
var options = new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "ReleaseTableBody",
OnBegin = "OnCallbackBegin",
OnFailure = "OnCallbackFailure",
OnSuccess = "OnCallbackSuccess",
LoadingElementId = "loading"
};
you can also use the event callback methods if you define their JavaScript functions like:
<script>
function OnCallbackBegin() {
$(".btn-loading-icon").show();
$(".btn-loading-text").hide();
}
function OnCallbackSuccess(data) {
//alert("onSuccess: result = " + data.result);
$(".btn-loading-icon").hide();
$(".btn-loading-text").show();
SomeOtherFunction();
}
I would also advise using the #Html.DropdownFor helper for your dropdowns.
I have a textbox that when the user enters a string and presses a button this is then compared to find which matching fields are in database. I also have another button that launches the display of a bootstrap modal which then views the results.
The issue I'm having is I only want one button but when I try to combine the two i get the modal and the string search never happens.
Can anyone tell me how I combine the two ?
Button 1 (search string button)
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
<label for="platform" class="control-label">Enter Code:</label><br />
#Html.TextBox("filtername")
<input type="submit" value="Filter" "/>
</p>
}
Button 2 (Activates modal but no data comparision)
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<div class="span7 text-center">
<input type="text" class="form-control" id="theCode" placeholder="Please Enter Code">
<input type="submit" value="Go!" class="btn btn-success" id="sendcoderequest" data-toggle="modal"
data-target="#basicModal2" />
</div>
</div>
</div>
Home/Index Method:
public ActionResult Index(string filtername)
{
var filterresults = from m in db.UserInfoes
select m;
filterresults = filterresults.Where(x => x.UserCode.ToString().Contains(filtername)).OrderBy(x => x.UserCode);
return View(filterresults);
}
Modal :
<div class="modal fade" id="basicModal2" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Summary</h4>
</div>
<div class="modal-body">
<h2>Results</h2>
<span id="printCode"></span><br />
<div class="pull-right"><button type="submit" class="btn btn-success" id="toggle">Toggle</button> </div>
<table class="table">
<thead>
<tr>
<th></th>
<th>Date</th>
<th>Test Type</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" class="checks">
</td>
<td>
#Html.DisplayFor(modelItem => item.CreationDateTime)
</td>
<td>
#Html.DisplayFor(modelItem => item.AppModeId)
</td>
</tr>
}
</tbody>
</table>
Code currently working with:
Form:
<form id="formid">
<label for="platform" class="control-label">Enter Code:</label>
<input type="text" name="filtername" />
<input type="submit" class="btn btn-success" value="Filter" />
</form>
JQuery:
$("#formid").submit(function () {
$.ajax({
url: "Home",
data: $(this).serialize()
}).done(function (response) {
$('#modal_content').html(response);
$('#basicModal2').modal('show');
});
return false; // prevent the form submission
});
Modal is unchanged.
You could use an AJAX call instead of the form submission. Then you could open the modal via Javascript once you receive the AJAX response. According to the tags, you're probably using JQuery, so it would look like this :
$("form").submit(function(){
$.ajax({
url: "Home",
data: $(this).serialize()
}).done(function(response){
// Fill your modal window with the response here
$('#basicModal2').modal('show');
});
return false; // prevent the form submission
});
Edit
You can find here an example that uses AJAX to send the filter name to the server, fill the modal with the server response and finally show the modal:
http://jsfiddle.net/yohanrobert/e3p4yv55/
In my mvc application i have a script with following code
<script type="text/javascript">
$(document).ready(function () {
var element = $('input[data-op-mode="Edit"]');
$(".form-control").attr("disabled", "disabled");
element.click(function() {
var elementValue = element.val();
if (elementValue == "Edit") {
element.val("Update");
$(".form-control").removeAttr("disabled");
return false; //blocking from submitting form
} else {
$(".form-control").attr("disabled", "disabled");
element.val("Edit");
return true;
}
});
});
</script>
The purpose this code is to toggle Edit->Update, Update->Edit. This functionality is working fine . but when submitting the form the the post method not submitting the form values to my controller (model binding not working). the html code is given below
#model AutoPosContextA.DomainModels.Customer
#{
var options = new AjaxOptions()
{
Url = Url.Action("Update", "Customer"),
LoadingElementId = "saving",
LoadingElementDuration = 1000,
OnFailure = "OnAjaxCallsFailed",
OnSuccess = "OnCustomerInsertSuccess"
};
}
#using (Ajax.BeginForm(options))
{
<ol class="breadcrumb">
<li><i class="fa fa-floppy-o"></i><input type="submit" value="Edit" class="btn-link" data-op-mode="Edit"/></li>
<li> <a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#mainDiv" href="/Customer/ListCustomer"><i class="fa fa-undo"></i> Cancel</a></li>
<li> <a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#mainDiv" href="/Customer/CreateCustomer"><i class="fa fa-eraser"></i> Clear</a></li>
</ol>
<div class="col-md-7">
<table class="table table-bordered table-striped" style="clear: both">
<tr>
<td><label for="CustomerName" >Customer name</label></td>
<td><input type="text" class="form-control" id="CustomerName" placeholder="Customer name" name="CustomerName" value="#Model.CustomerName"></td>
</tr>
<tr>
<td><label for="AddressLine1" >AddressLine-1</label></td>
<td><input type="text" class="form-control" id="AddressLine1" placeholder="AddressLine-1" name="AddressLine1" value="#Model.AddressLine1"></td>
</tr>
<tr>
<td><label for="AddressLine1" >AddressLine-2</label></td>
<td><input type="text" class="form-control" id="AddressLine2" placeholder="AddressLine-2" name="AddressLine2" value="#Model.AddressLine2"></td>
</tr>
<tr>
<td><label for="Mobile" >Mobile</label></td>
<td><input type="text" class="form-control" id="Mobile" placeholder="Mobile" name="Mobile" value="#Model.Mobile"></td>
</tr>
<tr>
<td><label for="CustomerKey" >Search Key(s)</label></td>
<td><input type="text" class="form-control" id="CustomerKey" placeholder="" name="CustomerKey" value="#Model.CustomerKey"></td>
</tr>
<tr>
<td><label for="Notes" >Notes</label></td>
<td><input type="text" class="form-control" id="Notes" placeholder="Notes" name="Notes" value="#Model.Notes"></td>
</tr>
</table>
<input type="hidden" value="#Model.Id" name="Id" id="Id"/>
</div>
}
The key point in my problems are
1.) If i remove the script it will work fine
2.) Here i am using strongly typed partial view
Whats wrong with my javascript?
Disabled form fields are not sent back to the server by the browser in a POST request (according to HTTP standards), so the MVC framework will not have the values to do the model binding before entering your controller.
Potential solutions
Avoid using disabled and mix some css and javascript to obtain the feeling of disabled for fields.
On form submit event make sure to enable all the fields back
Put some hidden fields in the form with the names from the controls, and update them every time a value changes.