Basically I want my code to update the textarea as users put a check in a checkboxes inside a table. If a checkbox is checked, a username will be placed in textarea along with line breaks. If unchecked, it will remove from textarea. After that, a button will submit every string inside the textarea.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
<td align="center">
<form>
<div style="max-width:50%" class="form-group #if (ViewBag.ErrorMessageDelete != null)
{ <text>has-error</text> } ">
#Html.TextArea("deleteRequest", string.Empty, 5, 100, null)
#if (ViewBag.ErrorMessageDelete != null)
{
<span class="help-block">#ViewBag.ErrorMessageDelete</span>
}
</div>
<button class="btn btn-primary" onclick="return confirm ('Removing these members, are you sure?')">Remove User(s)</button>
</form>
</td>
}
and this is my current checkbox
<td align="center" style="width:5%">
#Html.CheckBox("toBeDeleted", new { onclick = "deleteRequest = deleteRequest + item.username + <br>" });
</td>
I used textarea because I want users to be able to input usernames on their own without using checkboxes. Is it possible to do it in MVC ASP.NET in Visual Studio?
Don't do this with click event. Use change event on checkbox.
You can also try with the array. If the checkbox is checked add item to array, if not remove it. After that convert array to string, and set a value to textarea. Delete and push logic you have to implement by your own.
<td align="center" style="width:5%">
#Html.CheckBox("toBeDeleted", new { onchange="testfunc(this)", data_username = item.username });
</td>
<script>
var result = [];
function testfunc(elem) {
var username = $(elem).attr("data-username");
if($(elem).is(':checked')) {
result.push(username )
}
else{
var index = result.indexOf(username);
if (index > -1) {
result.splice(index, 1);
}
}
$("#deleteRequest").val(result.join("\n"));
}
</script>
Related
I am using Ajax.Begin form with a partial view to replace contents of defined target.
like so,
Partial View:
#model string
<fieldset style="width:916px">
<legend class="SearchFiledSet">AMN</legend>
<table>
<tr valign="top">
<td>Notes: </td>
<td>#Html.TextArea("Notes", #Model, 5, 30, new { disabled = "disabled", style = "background: #FFF; border: 1px solid #000;" })</td>
#using (Ajax.BeginForm("AMN", new AjaxOptions { UpdateTargetId = "AMN",
Url = Url.Action("AMN"),
OnBegin = "OnBegin",
OnFailure = "OnFailure",
OnSuccess = "OnSuccess",
OnComplete = "OnComplete"}))
{
<td style="padding-left: 30px">P N:   #Html.TextBox("PN", "", new { size = "15" })
#if(string.IsNullOrEmpty(#Model))
{
<br />
<font color="red">No matching pn was found in the system.</font>
}
</td>
<td style="padding-left: 60px">
<button type = "submit">Search</button>
</td>
}
</tr>
</table>
</fieldset>
Controller:
public PartialViewResult AMN(string PN = null)
{
IPS p=null;
string remarks= " ";
if (PN != null)
{
p = _pS.GetPPN.Trim());
remarks = p != null ? p.Remarks : remarks;
}
return PartialView(((object)remarks));
}
Main View:
<div id="AMN" style="margin-left: 180px">
#Html.Action("AMN")
</div>
The Ajax calls work fine in IE of course, but in Firefox it hits the break point on the controller and correctly posts during the first submit but then nothing will happen after each consecutive submit. Not even the break point will get hit. I have seen a few other posts of people complaining of this same issue a few years ago but none of them had a resolution. Has anyone experienced this issue and found a resolution or have any recommendations of what can be the issue?
There is another Html.BeginForm on the main page that I link my partial view to, but my partial view is outside that form, and I also tried removing the other form and just leaving the ajax one with no luck.
I am using jquery-1.7.2
I think I now understand what is happening based off of general research on the topic rather than directing it to Ajax.BeginForm method. I wanted to basically mimic a the concept of a panel, and be able to just plug in the full form and replace the panel (partial view) with updated data on the ajax call. Well I am not that experienced with ajax or javascript, but it seems that when I rewrite the html the object on the dom is getting replaced too so all focus is lost, hence it worked on one post but not twice.
This was confusing mostly because it worked the way I originally thought it would on Internet Explorer but not Firefox. So in order to make it cross-browser compatible I just used JSON to send back the data to be changed and then registered a function to the OnSuccess call, which will just change the html necessary rather than rebuilding the partial. I wanted to handle the Ajax mostly with the Asp.net MVC framework libraries to keep the code cleaner but I guess this isn't likely to happen unless I abstract out the form contents from the partial.
Here is the changes made for anyone else who runs into this issue:
Controller:
[HttpGet]
public PartialViewResult AMN()
{
string remarks = " ";
return PartialView(((object)remarks));
}
[HttpPost]
public JsonResult AMN(string PN = null)
{
IPS p=null;
string remarks= " ";
if (PN != null)
{
p = _pS.GetP(PN.Trim());
remarks = p != null ? p.Remarks : null;
}
return Json(remarks);
}
PartialView:
#model string
<fieldset style="width:916px">
<legend class="SearchFiledSet">AMN</legend>
<table>
<tr valign="top">
<td>Notes: </td>
<td>#Html.TextArea("Notes", #Model, 5, 30, new { disabled = "disabled", style = "background: #FFF; border: 1px solid #000;" })</td>
#using (Ajax.BeginForm("AMN", "PS", null, new AjaxOptions {OnSuccess = "processData" }, new { id = "AMNForm" }))
{
<td style="padding-left: 30px">PN:   #Html.TextBox("PN", "", new { size = "15" })
#if(string.IsNullOrEmpty(#Model))
{
<br />
<font color="red">No matching pn was found in the system.</font>
}
</td>
<td style="padding-left: 60px">
<button type = "submit">Search</button>
</td>
}
</tr>
</table>
</fieldset>
<s.. type="text/java..">
function processData(data) {
$("#Notes").val(data);
if (!data[0])
alert("data is null")
else
alert("data is not null")
}
</..>
We have partial view View1 as follows:
#using (Html.BeginCollectionItem)
{
<div id = "partialview-content>
<table >
<tr>
<td>
#Html.TextBoxFor(x=>x.Name, new {id = "name", #class = "name-class"})
// Additional controls
</td>
</tr>
<tr class="rowSpace">
<td>Label Text</td>
<td>
<span id="business-key-id">
#Html.DisplayFor(x=>x.BusinessKey)
</span>
</td>
</tr>
</table>
}
</div>
When user clicks on Add New Item in Main View, partial view will be added dynamically.
When user enters some text in name textbox in the dynamically added partial view, BusinessKey DisplayFor should be updated dynamically.
So I added below code in the JQuery:
$(document).ready(function () {
$(".name-class").live('keyup', function (event) {
var name1 = $("#name1").val();
var name2 = $("#name2").val();
var name = $(this).val();
(".business-key-id").html(trustName + ' ' + seriesName + ' ' + trancheName);
});
});
Doing this code is updating the business-key-id of all the dynamically added partial views. How can I get the control of the business-key specific to the keydown event control?
This line is selecting all elements with the class name business-key-id
$(".business-key-id").html(...
Change the selector to select only the next element
$(".name-class").on(...
$(this).next('.business-key-id').html(...
Note .live has been depreciated - you should use .on
Edit
Based on OP's revised html, the selector to choose the coresponding business-key-id should be
$(this).closest('table').find('.business-key-id).html(...
And change the html to use the class attribute, not id attribute (duplicate ID's are invalid html)
<span class="business-key-id">
#Html.DisplayFor(x=>x.BusinessKey)
</span>
I am working on asp.net MVC 4 application. I have created a list using foreach loop and declared a variable to show record number. Each row has a delete icon, which when clicked, deletes that record and hides that row. this works fine except one issue. When user deletes first record or any record in middle of list, I want the record number of all the rows to be updated accordinlgy.
Here is razor view code:
#{
int i = 1;
foreach (var item in cartItem.CartItemsByStore)
{
<tr id="cartrow-#item.CartItemID">
<td class="transaction">#i</td>
<td class="item-details">
<img src="/images/tmp/order-product.jpg" width="63" height="63">
<div class="desc">
<span>
<p>#item.ItemName</p>
</span>
</div>
</td>
<td class="date-time">15 Jun 2014</td>
<td class="action">
X
</td>
</tr>
<tr class="sp" id="sp-#item.CartItemID">
<td colspan="20"></td>
</tr>
i++;
}
}
and here is deletion code:
$(function () {
// Document.ready -> link up remove event handler
$(".removeCartItem").click(function () {
if (confirm("Click OK if you want to delete this record; otherwise, click 'Cancel'")) {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/Cart/DeleteCartItem", { "id": recordToDelete },
function (data) {
// Successful requests get here
$('#cartrow-' + recordToDelete).fadeOut('hide');
$('#sp-' + recordToDelete).fadeOut('hide');
$('#spCartCount').text(data);
$('#row-' + recordToDelete).fadeOut('hide');
});
}
}
});
});
Try this
Partial view : "Store.csthml"
#model IEnumerable<CartItemsByStore>
#{
int i = 1;
foreach (var item in Model)
{
<tr id="cartrow-#item.CartItemID">
<td class="transaction">#i</td>
<td class="item-details">
<img src="/images/tmp/order-product.jpg" width="63" height="63">
<div class="desc">
<span>
<p>#item.ItemName</p>
</span>
</div>
</td>
<td class="date-time">15 Jun 2014</td>
<td class="action">
X
</td>
</tr>
<tr class="sp" id="sp-#item.CartItemID">
<td colspan="20"></td>
</tr>
i++;
}
}
CartController:
public ActionResult ReturnView()
{
//populate model
IEnumerable<CartItemsByStore>model =db.GetItemsByStore();
return PartialView("Store",model)
}
public ActionResult DeleteCartItem(int id)
{
//delete
return RedirectToAction("ReturnView");
}
Main View:
<div id="divStore">
#Html.Partial("Store",cartItem.CartItemsByStore)
</div>
$(".removeCartItem").click(function () {
if (confirm("Click OK if you want to delete this record; otherwise, click 'Cancel'")) {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/Cart/DeleteCartItem", { "id": recordToDelete },
function (data) {
// Successful requests get here
$("#divStore").html(data);
});
}
}
});
I have some fields in a repeater and I need to validate them.
Here is the scenario:
When the page loads I get a set of fields just once(first name, last name etc.) and I get a link "Add another user", if you click the link it adds the same fields again on the bottom.
Now for the code part:
In my case I needed to run the repeater 4 times (so the fields are on the page 4 times from the begining). Then I hide them as I hide the <div> that contains them. When the button is clicked I show the first hidden div and so on.
Some code(not all):
<asp:Repeater ID="rptOtherPeople" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<td>
<h3>Други лица</h3>
</td>
</tr>
</thead>
<tbody class="GridBody">
</HeaderTemplate>
<ItemTemplate>
<tr class="GridRow" id="personRow" style="display: none">
<td>
<asp:TextBox ID="txtFirstName" CssClass="mid-inp" Text="" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
And here is that javascript that shows the next row:
$(document).ready(function () {
var peopleNum = 1;
if ($(".GridBody tr").length > 0) {
var tr = $(".GridBody tr")[0];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
var anc = tr.getElementsByTagName('a');
}
if ($(".GridBody tr").length > 0 && peopleNum > 0) {
for (i = 0; i < peopleNum; i++) {
var tr = $(".GridBody tr")[i];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
if (i > 0) {
var anc = tr.getElementsByTagName('a');
if (anc[i] != undefined)
anc[i].style.display = 'none';
}
}
}
})
function addPerson() {
var body = $(".GridBody");
var indexOfNextRow = $('tr[class="GridRow"][hidden="false"]').length;
var tr = $(".GridBody tr")[indexOfNextRow];
tr.style.display = 'table-row';
tr.setAttribute('hidden', 'false');
}
The Problem: For example I want the field to be required. I put a RequiredFieldValidator and I disable it in some cases and enable it in others. The thing is that I get 4 RequiredFieldValidators on the page and I can only turn ALL of them on or off at once. I want to activate just one of them. I couldn't find a way to do that because they are pretty much identical. Any ideas?
I assume that I can not sort this out in the code behind. Can I work with just one RequiredFieldValidator via javascript(how do I identify the one I want).
Some people prefer jquery validation. Is it applicable in this case and how(I have never used jquery validation before)?
EDIT 1
Ok the controls are not identical. In the browser the generated ID is: ctl00_SPWebPartManager1_g_f6926ea5_98ba_46c1_b157_4f1ddc46885d_ctl00_Step21_otherPeople_rptOtherPeople_ctl01_rv1 , but I can not access the validator from here in my Javascript
You can disable the validators either server side or client side.If i understood your question , the thing you looking for is disabling a specific vaidator say required field validator.For that here is a simple javascript code to disable the validators.
function DisableRFValidators() {
var ValidatorToDisable = document.getElementById("RequiredFieldValidator2");
ValidatorEnable(ValidatorToDisable, false);
}
Fixed it! Here is the code:
$("#aspnetForm").validate();
$(".required").each(function (index) {
if ($(this).attr("id").indexOf("txtFirstName") >= 0) {
$(this).rules("add", {
required: true,
minlength: 3,
messages: {
required: "<div class='val' style='color:red'>Name is Required!</div>",
minlength: "<div class='val' style='color:red'>Minimum number of symbols = 3!</div>"
}
});
}
else if ($(this).attr("id").indexOf("txtFirstName") >= 0){
$(this).rules("add", {
required: false
});
}
});
function validateData() {
var result = $("#aspnetForm").valid();
return result;
}
function btnNextClick(btn_this) {
var btnNext = document.getElementById("<%=btnMoveNextHidden.ClientID%>");
if (btnNext != null && validateData() == true) {
btnNext.click();
}
}
I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
<div id="newUserDialog">
#using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
#Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
Javascript code for Save User on the dialog being clicked - submit the form.
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
return PartialView("UserSuccess", model);
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my _Layout page)
#model MyProject.Models.UserModel
#{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
Are you sure that your initial html do have a #resultContainer div? If you don't the
$('#resultContainer').html(result);
line won't match anything. If you do on the other hand, you will get duplicate nested #resultContainer divs which is also an error (id must be unique).
The right way to do it is to add an empty div in your original html:
<div id="resultContainer"></div>
And in your view output just the content to go inside the div.
#model MyProject.Models.UserModel
#{
ViewBag.Title = "UserSuccess";
}
User Created Successfully
I have to say what you are doing is not a good way of using dialog and partial view in ASP.NET MVC applications. I can give you some simple code to show an idea:
If list.cshtml is a list of users page, and edit.cshtml is a partial view that has an edit form in.
On list page:
$(".grid-row .edit").click(function(){
editUser($(this).attr("data-id"));
});
function editUser(id){
var $dialog=$("#dialogEditUser");
if($dialog.length == 0){
$dialog=$("<div id='dialogEditUser'>").appendTo("body");
}
$dialog.dialog({
...
open:function(){
$dialog.load("/user/edit/"+id, function(){
//todo: handle form events
});
}
});
$dialog.dialog("open");
}
You can also make the open dialog function in a static method, like:
MvcSolution.Dialog = function (id, title, options) {
var $dialog = $("#" + id);
if ($dialog.length == 0) {
$dialog = $("<div id='" + id + "' class='dialog' title='" + title + "'></div>").appendTo("body");
}
$dialog.dialog(options);
$dialog.dialog("open");
};
You can find a good c# and js framework for MVC here