How to read arrays generated by EditorFor using jQuery - asp.net

I am quite confused with technique that I am using. I am using EditorFor to display values.
The code for the values to be generated are as follows:
<tr>
<td>#Html.HiddenFor(m => m.ID)#Html.CheckBoxFor(m => m.Authorized)</td>
<td>#Html.DisplayFor(m => m.ID)</td>
<td>#Html.DisplayFor(m=>m.UserName) </td>
</tr>
My aim here is upon the Checkbox is being checked, I need to post the ID value as follows:
$("input:checkbox").live('click', function () {
if ($(this).attr('checked')) {
var ID = $(this).parent().parent().find('#ID').val();
$.ajax({
type: "POST",
url: '<%=Url.Action("Edit","Employee") %>',
data: JSON.stringify(ID),
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function () {
},
error: function (request, status, error) {
alert("Error: " & request.responseText);
}
});
} });
However, var ID = $(this).parent().parent().find('#ID').val(); is undefined. How can I he read the ID value from the following generated HTML:
<td><input id="Employee_0__ID" name="Employee[0].ID" type="hidden" value="1100" /><input id="Employee_0__Authorized" name="Employee[0].Authorized" type="checkbox" value="true" /><input name="Employee[0].Authorized" type="hidden" value="false" /></td>
<td>user </td>

Not sure I understand what value you looking for?
Would this.
var ID = $(this).parent().parent().find('#ID').attr('value');
or this
var ID = $(this).parent().parent().find('#ID').attr('id');
work?

For the HTML specified this should suffice as the hidden element is the previous sibling of the checkbox in the DOM
var ID = $(this).prev().val();

Related

get table column value of selected row in table asp.net in jQuery

I am working on asp.net mvc project.
I want to get the cell value from the selected row (row in which "Manage "button is clicked).
in this case value of userID.
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th width="45%">User ID</th>
<th width="45%">User Name</th>
<th width="5%">View</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TypeList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
<input id="Manage2" class="btn btn-primary" type="button" value="Manage" />
</td>
</tr>
}
</tbody>
I am calling jQuery click function and Ajax call and want to send the UserId value in data from selected row to the controller.
below is the jQuery ajax call,
<script type="text/javascript">
$(document).ready(function () {
$('#Manage2').click(function () {
//alert(1);
var url = '#Url.Action("ManageUserRole", "UserRoleCompany")';
$.ajax({
url: url,
data: { Id: '1' },
cache: false,
type: "POST",
success: function (data) {
$("#Data").html(data);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
});
</script>
Below is the view screen shot,
You can actually store the UserId value with html 5 data attribute on the button itself.
Your current code has Id attribute value hard coded inside a loop, which will create more than one element with same Id value. That is invalid HTML!
Remove the Id and use a more generic selector to wire up the click event. Here I added another CSS class "manage" to the button.
<input data-userid="#item.UserId" class="btn btn-primary manage"
type="button" value="Manage" />
and now
$(document).ready(function () {
$('.manage').click(function () {
var id = $(this).data("userid");
alert(id);
// use id for your ajax call
});
});
You do not necessarily need to add the extra css class only to use that as the selector later. Since you are adding a data attribute, you may simply use that as well for your jQuery selector.
$(function () {
$('[data-userid]').click(function () {
var id = $(this).data("userid");
alert(id);
// use id
});
});
You have invalid html because of the duplicate id attributes in your button.
Remove the id="Manage2" and replace with a class name and data- attribute for the value
<input data-id="#item.UserId" class="btn btn-primary Manage2" type="button" value="Manage" />
Then in the script, get the value using
$('.Manage2').click(function () { // class selector
var id = $(this).data('id);
var url = '#Url.Action("ManageUserRole", "UserRoleCompany")';
$.ajax({
url: url,
data: { Id: id },
....
Alternatively you could use relative selectors
$('.Manage2').click(function () {
var id = $(this).closest('tr').children('td:first').text();
....

Large file streaming confusion

I want to handle large files in my application and microsoft documentation about File Uploads looks so bizarre. Why would I need MultipartReader whereas I would simply achieve what I want with the following:
#model SampleVM
<form method="post" enctype="multipart/form-data">
<input asp-for="Prop1" />
<input asp-for="Prop2" />
<input type="button" value="Ok" onclick="post();"/>
</form>
#section Scripts{
<script>
function post() {
var formData = new FormData();
formData.append('Prop1', $('#Prop1').val());
formData.append('Prop2', $('#Prop2')[0].files[0]);
$.ajax({
url: '#Url.Action("Index")',
type: 'POST',
processData: false,
contentType: false,
data: formData
});
}
</script>
}
and in the controller I can simply get the stream with
var stream = vm.Prop2.OpenReadStream()
and do whatever I want. What does Microsoft documentation achieve with that spaghetti code that I don't with this simple sample?

Use AJAX to submit data from HTML form to WebMethod

So I'm taking in data from an HTML form and then using AJAX to send the data to a web method to then be sent to a sqlite database, but my AJAX call is failing. What did I mess up? Am I doing it correctly?
HTML Form
<form id="addForm" >
<input type="text" name="playername" id="playername" placeholder="Player"/>
<input type="text" name="points" id="points" placeholder="Points" />
<input type="text" name="steals" id="steals" placeholder="Steals" />
<input type="text" name="blocks" id="blocks" placeholder="Blocks" />
<input type="text" name="assists" id="assists" placeholder="Assists" />
<input type="text" name="mpg" id="mpg" placeholder="MPG" />
<input type="text" name="shotpct" id="shotpct" placeholder="Shot %" />
<input type="text" name="threepct" id="3pct" placeholder="3 %" />
<input type="button" value="add player" id="addbtn" name="addbtn" />
</form>
AJAX
$("#addbtn").click(function () {
var form = $("#addForm").serializeArray();
$.ajax({
type: 'POST',
url: "players.aspx/addRow",
data: JSON.stringify(form),
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
and the web method(not finished, was just testing to see if I was getting data)
[WebMethod]
public static void addRow(object form)
{
var stuff = form;
}
I'm still learning how to use a lot of this stuff so any help will be greatly appreciated.
Replace
type: 'POST',
with
method: 'POST',
dataType: 'json'
is not needed since you're not receiving data back. The data returned from the server, is formatted according to the dataType parameter.
Also remove JSON.stringify(form),this is already done with the .serialize();
replace
JSON.stringify(form)
with
$('form').serializeArray()
So you will have:
$("#addbtn").click(function () {
var form = $("form").serializeArray();
$.ajax({
type: 'POST',
url: "players.aspx/addRow",
data: form,
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
If you still get error. there might be a server side problem in the page you are calling. to make sure of that I suggest you use the 'Advanced REST client' witch is a Google Chrome extension and you can test posting values with it and see the result.

How to pass one (or more) parameter(s) through a button

First of all ASP.NET MVC is very new to me (+- one month).
In my view I've got this code
First block
<label for="from">Data Inicio</label>
<input id="from" name="from" type="text" />
<label for="to">Data Fim</label>
<input id="to" name="to" type="text" />
Second block
<div class="btn-group">
<button type="button" class="btn btn-primary" onclick="listaC006()">Pesquisa Normal</button>
<button type="button" class="btn btn-primary" onclick="flistaC006()">Pesquisa com filtro</button>
</div>
and also
function list() {
$.ajax(
{
type: 'POST',
url: '/Inscricao/_Lista',
dataType: 'html',
cache: false,
async: true,
success: function (data) {
$('#lista').html(data);
}
});
}
in order to fill this "<div id="lista"></div>" dynamically.
It's possible to pass the values (datepicker) of "from" and "to" in the onclick event in order to use those values to perform a query?
To pass parameters on your post add the data argument to your post call:
function list() {
$.ajax(
{
type: 'POST',
url: '/Inscricao/_Lista',
dataType: 'html',
cache: false,
async: true,
data: "{'from': '" + $("#from").val() + "', 'to': '" + $("#to").val() + "' }",
success: function (data) {
$('#lista').html(data);
}
});
}

Where is this "Too Many Characters in String literal" message coming from?

Good morning all,
I'm sure this is a gimme, but I have no idea where this issue is coming from.
I have the following lines in a view:
<fieldset>
<dl>
<dt>
<label for="FormTypes">Form Type:</label>
</dt>
<dd>
<% =Html.DropDownList("FormTypes", "All") %>
</dd>
</dl>
</fieldset>
<fieldset>
<dl>
<dt>
<label for="Parts">Form Part:</label>
</dt>
<dd>
<% =Html.DropDownList("Parts", "All") %>
</dd>
</dl>
</fieldset>
This causes no problems, but when adding the following script to the top of to update Parts based on the selection of form type (following the answer to this SO question Bind DropDownlists with JQuery in Asp.Net)
<script type="text/javascript">
<!--
$('#FormTypes').change(function() {
var val = $(this).val();
$parts = $('#Parts');
$.ajax({
url: '<%= Url.Action('FormParts') %>',
dataType: 'json',
data: { ID: val },
success: function(parts) {
$.each(parts, function(i, part) {
$parts.append('option value="' + part.ID+ '">' + part.Code + '</option>');
});
},
error: function() {
alert('Failed to retrieve parts list.');
}
});
});
//-->
</script>
(where the FormParts action will return a new object to populate the parts drop down list)
I get the message: Too many characters in character literal on the line
<% =Html.DropDownList("Types") %>
It appears this issue is caused by the javascript being added, but why and why the error is on the previously good line of code in the markup and not in the script?
Thanks in advance.
While there's nothing wrong with the line you seperated out, this part in the original code does bother me:
<%= Url.Action('FormParts') %>
You used single quotes for the string in ASP. This marks it as a character literal, and not a string. Replace them with double quotes and you should be fine.
<%= Url.Action("FormParts") %>
I'm not sure where that issue was coming from, I've updated the script to the following and it works.
<script type="text/javascript">
<!--
$(function() {
$('#FormTypes').change(function() {
//clear all items in list and replace "All" option
$parts = $('#FormParts');
$parts.html("");
$parts.append('<option value="">All</option>');
var selectedValue = $(this).val();
if (selectedValue != "") {
$.ajax({
url: '<%= Url.Action("FormParts") %>',
dataType: 'json',
data: { FormTypeID: selectedValue },
success: function(parts) {
//repopulate list with JSON objects
$.each(parts, function(i, part) {
$parts.append('<option value="' + part.ID + '">' + part.Code + '</option>');
});
},
error: function() {
alert('Parts list could not be retreived. \n Please use the feedback link to inform us');
}
});
}
});
});
//-->
</script>
For anyone using this code, in future, please note I've added the evaluation
if (selectedValue != "")
this has been added if the option "All" is selected in the first FormTypes drop down list, there is no dependent part list that should be populated.

Resources