MVC 3: Why is jquery form.serialize not picking up all the controls in my form? - model-view-controller

I am trying to create a situation where if a user clicks on an "edit" button in a list of text items, she can edit that item. I am trying to make the "edit" button post back using ajax.
Here's my ajax code:
$(function () {
// post back edit request
$('input[name^="editItem"]').live("click", (function () {
var id = $(this).attr('id');
var sections = id.split('_');
if (sections.length == 2) {
var itemID = sections[1];
var divID = "message_" + itemID;
var form = $("#newsForm");
$.post(
form.attr("action"),
form.serialize(),
function (data) {
$("#" + divID).html(data);
}
);
}
return false;
}));
});
But the form.serialize() command is not picking up all the form controls in the form. It's ONLY picking up a hidden form field that appears for each item in the list.
Here's the code in the view, inside a loop that displays all the items:
**** this is the only control being picked up: ******
#Html.Hidden(indexItemID, j.ToString())
****
<div class="datetext" style="float: right; margin-bottom: 5px;">
#Model.newsItems[j].datePosted.Value.ToLongDateString()
</div>
#if (Model.newsItems[j].showEdit)
{
// *********** show the editor ************
<div id="#divID">
#Html.EditorFor(model => model.newsItems[j])
</div>
}
else
{
// *********** show the normal display, plus the following edit/delete buttons ***********
if (Model.newsItems[j].canEdit)
{
string editID = "editItem_" + Model.newsItems[j].itemID.ToString();
string deleteID = "deleteItem_" + Model.newsItems[j].itemID.ToString();
<div class="buttonblock">
<div style="float: right">
<input id="#editID" name="#editID" type="submit" class="smallsubmittext cancel" title="edit this item" value="Edit" />
</div>
<div style="float: right">
<input id="#deleteID" name="#deleteID" type="submit" class="smallsubmittext cancel" title="delete this item" value="Delete" />
</div>
</div>
<div class="clear"></div>
}
It's not picking up anything but the series of hidden form fields (indexItemID). Why would it not be picking up the button controls?
(The ID's of the edit button controls, by the way, are in the form "editItem_x" where x is the ID of the item. Thus the button controls are central to the whole process -- that's how I figure out which item the user wants to edit.)
UPDATE
The answer seems to be in the jquery API itself, http://api.jquery.com/serialize/:
"No submit button value is serialized since the form was not submitted using a button."
I don't know how my action is supposed to know which button was clicked, so I am manually adding the button to the serialized string, and it does seem to work, as inelegant as it seems.
UPDATE 2
I spoke too soon -- the ajax is not working to update my partial view. It's giving me an exception because one of the sections in my layout page is undefined. I give up -- I can't waste any more time on this. No Ajax for this project.

You could try:
var form = $('#newsForm *'); // note the '*'
Update
Did you change the argument to $.post() as well? I think I may have been a little too simple in my answer. Just change the second argument within $.post() while continuing to use form.attr('action')
New post should look like this:
$.post(
form.attr("action"),
$('#newsForm *').serialize(), // this line changed
function (data) {
$("#" + divID).html(data);
}
);

Related

MVC calling a script with a key

I have a button that calls data to textboxes. But I want to do this with the enter key, not with a button.
This script calls the datas.
<script>
function AboneBul() {
location.href = "/Home/AboneBul/" + document.getElementById('ABONE_NO').value + "";
}
And this piece of code is the buttons code.
<div>
<input type="button" class="btn btn-success" onclick="AboneBul()" value="Abone Getir" />
</div>
Can someone help me please?
this example from w3school, it might help somehow.
// Get the input field
var input = document.getElementById("myInput");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});
the source link

Get the ID from a button which has a dynamic ID

I can not grasp my mind around this.
I am making a ajax call into a servlet. The problem is, on the page that is displayed, i could have 1-20 different buttons that needs to recall the same servlet. So I have the following form...
<form id="ajax-contact">
<input type="text" value="${item.transactionId}" id="transactionId" name="transactionId"/><br>
<input type="text" value="deliveryReceipt" id="action" name="action"/><br>
<input type="text" value="${item.id}" id="id" name="id"/><br>
<button type="submit" id="${item.id}" class="btn btn-primary" data-toggle="modal" data-target=".${item.id}">view delivery receipt</button>
</form>
In my ajax, I have this...
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
//var formData = $(form).serialize();
var id = $("#id").val();
var tranid = $("#transactionId").val();
var action = $("#action").val();
var dataFromForm = "trannsactionId="+tranid+"&action="+action+"&id="+id;
alert(dataFromForm);
alert(formData);
// Submit the form using AJAX.
$.ajax({
url : "Controller",
type: "GET",
data : dataFromForm,
dataType: "json",
})
.success(function(response) {
...
I am trying to make it so the ajax call uses the params for the specific set of information within the form. How can I do this?
Thanks!
More detail:
Once this page shows, if I have 10 sections on there with a button. When I click on the first view delivery receipt button, it works fine.
If I go down my list and click on t he 8th view delivery receipt, itll make an ajax call for the first form.

Load partial view depending on dropdown selection in MVC3

Im trying to create a from using asp.net mvc3.
I have a dropdownlist with some options.
What i want is different partial views to be injected into the page, depending on the selection in the dropdown list.
But. i dont want this to rely on a submit action. It should function so that, the partial view is loaded as soon as you select from the select list.
I have this code:
#using (Ajax.BeginForm("Create_AddEntity", new AjaxOptions {
UpdateTargetId = "entity_attributes",
InsertionMode = InsertionMode.Replace
}
))
{
<div class="editor-label">
#Html.Label("Type")
</div>
<div class="editor-field">
#Html.DropDownList("EntityTypeList", (SelectList)ViewData["Types"])
</div>
<div id="entity_attributes"></div>
<p>
<input type="submit" value="Create" />
</p>
}
But I can't figure out how to trigger this partial view load when the dropdown list selection changes.
This point is that the form is different for the different "entity types". so there will be loaded a different partial view, depending on the dropdown selection.
Anyone got any pointers?
Let's say following is your view that you want to insert your partial.
<html>
<head><head>
<body>
<!-- Some stuff here. Dropdown and so on-->
....
<!-- Place where you will insert your partial -->
<div id="partialPlaceHolder" style="display:none;"> </div>
</body>
</html>
On the change event of your dropdownlist, get partial via jquery ajax call and load it to place holder.
/* This is change event for your dropdownlist */
$('#myDropDown').change( function() {
/* Get the selected value of dropdownlist */
var selectedID = $(this).val();
/* Request the partial view with .get request. */
$.get('/Controller/MyAction/' + selectedID , function(data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
And in your controller action which is /Controller/MyActionin above jquery, return your partial view.
//
// GET: /Controller/MyAction/{id}
public ActionResult MyAction(int id)
{
var partialViewModel = new PartialViewModel();
// TODO: Populate the model (viewmodel) here using the id
return PartialView("_MyPartial", partialViewModel );
}
add the following code to the header of the project (layout).
Add "combobox" to any combo box (select box) which you want to trigger the form that is surrounding it.
$(document).ready(function () {
$('.formcombo').change(function () {
/* submit the parent form */
$(this).parents("form").submit();
});
});

Reloading main view after button in PartialView is clicked

I have a partial view that the user can preform a search in, and the search results are shown in a select box. In my main view I have a section that is supposed to show the search results after a select button is pressed. Right now when I click the select button is loads the correct information into the correct model for my main view, but the main view doesn't change. When I click refresh, the page updates correctly. How do I make the page update automatically when a button is clicked in the plugin view?
My section in the main view (Index.vbhtml) in my main app:
#Section CUInfo
Credit Union Name: #Model.CUInfo.CUName
end section
Here is my controller method in my Plugin:
Function ChangeCUInfo(strCUName As String) As ActionResult
m_hostApp.CUInfo.CUName = strCUName
m_hostApp.blnPluginRefreshButtonPressed = True
Return View("Index", m_hostApp)
End Function
I've tried to set a boolean value in the hostApp object and then in my main razor view call this function if it is true:
#code
If Model.blnPluginRefreshButtonPressed = True Then
#<script type="text/javascript">
$(function () {
window.location.reload();
});
</script>
End If
Model.blnPluginRefreshButtonPressed = False
End Code
EDIT:
JS function called when the select button is clicked:
function loadCU(CUInfo) {
strCU = CUInfo.split('|');
strCUName = strCU[0];
$.ajax({
type: "POST",
url: "/CUContractNumberPlugin/ChangeCUInfo",
data: { "strCUName": strCUName }
});
}
Form that is used in the plugin view:
#Using (Html.BeginForm("ChangeCUInfo", "CUContractNumberPlugin"))
#<div id="LogoSigSearch" style="height:300px;width:500px;position:relative;">
<span style="display:inline-block;height:20px;width:166px;position:absolute;top:35px;left:5px;">Credit Union Name</span>
<br />
#Html.TextBox("strCUName")
<input type="submit" name="LogoSigSearch$ctl02" value="Search" id="LogoSigSearch_ctl02" tabindex="3" style="width:60px;position:absolute;top:5px;left:352px;" />
<input name="LogoSigSearch$ctl05" type="button" onclick="javascript:clearSearch()" value="Clear" style="position:absolute;top:35px;left:352px;width:60px;" />
<select size="4" name="LogoSigSearch$ctl06" id="LogoSigSearch_ctl06" tabindex="5" style="height:230px;width:342px;position:absolute;top:65px;left:5px;"></select>
<input type="button" name="SelectCU" value="Select" onclick="javascript:loadCU(LogoSigSearch_ctl06.options[LogoSigSearch_ctl06.selectedIndex].value)" tabindex="4" style="width:60px;position:absolute;top:65px;left:352px;" />
</div>
End Using
Are both buttons part of a form? A button won't invoke an action without you attaching it to script or making it part of a form with an associated action.
Use a partial view to render the results of the query, even on the main page load. This simplifies your development.
Add a jQuery event handler (jQuery.on()) to watch for the button click on your main page, or if the button is returned in the partial view, just use an on ready handler in your partial and attach a button.click() event, again using jQuery.
The jQuery event handler can take care of submitting the values of the query, posting to your controller, and displaying the results. I have a number of older articles here but they are still relevant to your question and demonstrate submitting data and fetching partials.
Your client-side code will end up looking something like this:
$("#your-button").click(function () {
var fetchUrl = '#Url.Action("ActionName", "Controller")';
$.post(fetchUrl, { searchParams: $("#your-search-box").val() })
.success(function (data) {
// replace the contents of the DIV with the results. 'data'
// here has whatever you sent back from your partial view
})
.error(function (data) {
// handle the error, use a DIV with some kind of alert message etc
});
});
Hope this helps some.

Multiple dropdownlist postback in MVC3

I have the following code on a view:
#using (Html.BeginForm()) {
<div class="select-box form">
<p>
<strong>Select transcript name to view:</strong>
#Html.DropDownList("license", (SelectList)ViewBag.Licenses, new { onchange = "this.form.submit();" })
</p>
</div>
<div class="select-box form">
<p>
<strong>You may have multiple periods for each transcript name:</strong>
#Html.DropDownList("period", (SelectList)ViewBag.Periods, new { onchange = "this.form.submit();" })
</p>
</div>
}
I need to implement some logic depending on which dropdown cause the postback. I'm thinking to add a hidden input and set value of the control name by jQuery before submit the form, but I'm wondering if there is a 'native' way to do this.
This is my controller signature:
public ActionResult Checklist(int license, int period)
Thanks in advance!
I would apply a class to the dropdown so that my jQuery can use that as the selector criteria
#Html.DropDownList("license", (SelectList)ViewBag.Licenses, new { #class="mySelect"})
#Html.DropDownList("period", (SelectList)ViewBag.Periods, new { #class="mySelect"})
<input type="hidden" id="source" name="source" value="" />
And the script is
$(function(){
$(".mySelect").change(function(){
var itemName=$(this).attr("name");
$("#source").val(itemName);
$("form").submit()
});
});
Use something like this. (Here you are calling the action method instead of submitting the form)
Which ever dropdown caused the change will pass non zero value to the action method and the other will pass 0.
#Html.DropDownList("license", (SelectList)ViewBag.Licenses, new { onchange = "document.location.href = '/ControllerName/Checklist?license=' + this.options[this.selectedIndex].value + '&period=0'" })
#Html.DropDownList("period", (SelectList)ViewBag.Periods, new { onchange = "document.location.href = '/ControllerName/Checklist?license=0&period=' + this.options[this.selectedIndex].value;" })
Hope this helps!

Resources