SignalR Chat: Differentiating ListItem sender and receiver for Css - javascript

I'm building a small ChatHub application based on the Microsoft-Tutorial for SignalR and JavaScript.
In short: hub-messages are put in a created-on-demand (li)
For styling purposes I'm looking to add a classname to these (li), differentiating them into categories "sender" and "receiver"
Background:
Each Side of the ChatConnection has a different view. I'm still building on the logic of the texting, so this is far from flawless.
My dbo for friendstable is UserFriends, depending on which side of the friendship you are, you get a different (but mirrored) chatwindow.
Cshtml-snippet:
#foreach (var item in Model.UserFriends)
{
#if (item.FriendChatName == #User.Identity.Name)
{
<div>
<button class="open-button" onclick="openChatForm()">#item.UserChatName</button>
<div class="chat-popup" id="myChatForm" style="display:none">
<form action="/action_page.php" class="form-container">
<button type="button" class="btn cancel" onclick="closeChatForm()">#item.UserChatName</button>
<input type="hidden" id="receiverInput" value="#item.UserChatName"/>
<ul id="messagesList" class="chatmessage receiver" ></ul>
<input type="hidden" id="userInput" class="receiverInput" value="#item.FriendChatName" />
<textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
<button type="submit" asp-route-user="#User.Identity.Name" asp-route-sender="#User.Identity.Name" asp-route-receiver="#item.UserChatName" class="btn" id="sendButton">Send</button>
</form>
</div>
</div>
}
#if (item.UserChatName == #User.Identity.Name)
{
<div>
<button class="open-button" onclick="openChatForm()">#item.FriendChatName</button>
<div class="chat-popup" id="myChatForm" style="display:none">
<form action="/action_page.php" class="form-container">
<button type="button" class="btn cancel" onclick="closeChatForm()">#item.FriendChatName</button>
<input type="hidden" id="receiverInput" value="#item.FriendChatName" />
<ul id="messagesList" class="chatmessage sender" ></ul>
<input type="hidden" id="userInput" value="#item.UserChatName" />
<textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
<button type="submit" asp-area="" asp-route-user="#User.Identity.Name" asp-route-sender="#User.Identity.Name" asp-route-receiver="#item.FriendChatName" class="btn" id="sendButton">Send</button>
</form>
</div>
</div>
}
}
the ChatHub Class:
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
and the chat.js script-snippet:
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + ": " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
I'm trying to get this kind of thing:
if (user == reciever ) {
li.className = "receiver";
}
if (user == sender) {
li.className = "sender";
}
With the help of this snippet
var sender = document.getElementById("senderInput").value;
var receiver = document.getElementById("receiverInput").value;
But when all smoothed out i get nothing but a runtime error
this is the view in two browser windows
Anybody can help me with the building of the If in the chat.Js or has other structural notes on how i would go about styling sendermessenges and receivermessages differently, would be much appreciated!

I'm back to post my solution for this problem:
#foreach (var item in Model.User.Friends)
{
<li>
<button class="open-button" onclick="openChatForm(event, '#item.Id##ChatForm')" type="button" style="max-width:200px;">#item.UserName</button>
<div class="chat-popup" id="#item.Id##ChatForm" style="display:none; width:300px; margin-left:900px;">
<div>
<form action="/action_page.php" class="form-container" style="position:absolute">
<button class="btn cancel" onclick="closeChatForm(event, '#item.Id##ChatForm')" type="button">#item.FirstName</button>
<input type="hidden" id="receiverInput" value="#item.UserName" />
<ul id="messagesList" class="chatmessage" style="max-height:600px;"></ul>
<input type="hidden" id="senderInput" value="#User.Identity.Name" />
<textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
<button type="submit" class="btn" id="sendButton">Send</button>
</form>
</div>
</div>
<script>
</script>
</li>
}
this is the chat.js
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + ": " + msg;
var li = document.createElement("li");
li.className += user;
var senderForSenderForm = document.getElementById("senderInput").value;
var senderForReceiverForm = document.getElementById("receiverInput").value;
var receiverForSenderForm = document.getElementById("receiverInput").value;
var receiverForReceiverForm = document.getElementById("senderInput").value;
if (senderForSenderForm === li.className ) {
li.className += " toRight";
}
if (receiverForSenderForm === li.className) {
li.className += " toLeft";
}
if (senderForReceiverForm === li.className ) {
li.className += " toRight";
}
if (receiverForReceiverForm === li.className) {
li.className += " toLeft";
}
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("senderInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
ChatHub is still the same..
In short i refactored the chatwindow to one scope,
generated (li)'s for messages and adding a class to it to finally base the styling off this className.
Styling for all friends is Okay, Chatting atm is just possible with one friend, will update when fixed!

Related

Comments feauter with JavaScript: who knows why condition on line 53 doesn't work?

I add text "You are answering:" in to block #aname, then it is checked if there is such text in that block, then the code should be executed but it doesn't. This is first time I'm writing on JavaScript so maybe the code seems trash but anyway want to understand what the problem is here otherwise I need to rewrite the hole code in a different way.
let comments = [];
document.getElementById('comment-button').onclick = function() {
event.preventDefault();
let commentatorsName = document.getElementById('cname');
let commentatorsEmail = document.getElementById('cmail');
let commentatorsMessage = document.getElementById('cmsg');
let comment = {
name : commentatorsName.value,
email : commentatorsEmail.value,
msg : commentatorsMessage.value,
time : Math.floor(Date.now()/1000)
}
commentatorsName.value = '';
commentatorsEmail.value = '';
commentatorsMessage.value = '';
comments.push(comment);
showComments();
}
//Adding text to aname div block in html
let amountAnswers = document.getElementsByClassName('reply').length;
for (let i = 0; i < amountAnswers; i++){
document.getElementsByClassName('reply')[i].onclick = function() {
console.log('This never happens');
let tag = document.getElementById("aname");
let text = document.createTextNode("You are answering:");
tag.appendChild(text);
}
}
function showComments() {
let commentsField = document.getElementById('commentsField');
let out = '';
let itbe = document.getElementById('aname');
//This condition is written correctly but doesnt work for some unknown reason
console.log('itbe: ' + itbe.textContent);
if (itbe.textContent.includes("You are answering:")) {
comments.forEach(function(item) {
out += `<p class="time"><em>answered ${item.time}</em></p>`;
out += `<p class="name" style="margin-left: 27px;"> From: <strong>${item.name}</strong></p>`;
out += `<p class="message" style="margin-left: 27px;">${item.msg}<br><button class="reply" type="submit" style="background: transparent; margin-left: 30px;">Reply</button></p><br>`;
});
commentsField.innerHTML = out;
}
//It runs this code instead
else {
comments.forEach(function(item) {
out += `<p class="time"><em>${item.time}</em></p>`;
out += `<p class="name">From: <strong>${item.name}</strong></p>`;
out += `<p class="message">${item.msg}<br><button class="reply" type="submit" style="background: transparent; margin-left: 30px;">Reply</button></p><br>`;
});
commentsField.innerHTML = out;
}
}
<p id="comlabel">Comments<p>
<div id="commentsField">
</div>
<form>
<div id="aname">
</div>
<ul>
<li>
<label for="cname">Name:</label>
<input type="text" id="cname" name="user_name" />
</li>
<li>
<label for="cmail">E-mail:</label>
<input type="email" id="cmail" name="user_mail" />
</li>
<li>
<label for="cmsg">Message:</label>
<textarea id="cmsg" name="user_message"></textarea>
</li>
<li class="button">
<button type="submit" id="comment-button">Send message</button>
</li>
</ul>
</form>
<script src="scripts.js"></script>

How to ensure only 1 box will be created?

I have a web application that allows users to duplicate boxes which are elements.However i am having a slight problem.Everytime when i click one the button to duplicate the box,there will have multiple boxes appearing when there should be just 1 box.How do I fix this issue?
JQUERY:
function getElem(element) {
var name = $(element).attr('name');
console.log(name);
var dupBtn = document.getElementById('duplicateBox');
$(dupBtn).on('click', function () {
var check = document.getElementById("box0");
if (check === null || $(check).attr('name') == null) {
$(document.getElementById('errorMessage')).text("Please create a box and label it first");
document.getElementById('errorMessage').style.display = 'block';
alert("Please create a box and label it first");
}
else{
document.getElementById('errorMessage').style.display = 'none';
document.getElementById("save").style.pointerEvents = ("auto");
var div = document.createElement('div');
$(div).attr('id', 'box' + i);
$(div).attr('class', 'box');
$(div).attr('name', name);
div.style.width = element.style.width;
div.style.height = element.style.height;
div.style.border = element.style.border;
div.style.background = element.style.background;
$(div).draggable({
containment: "#canvas"
});
$(div).resizable({
handles: 'ne, se, sw, nw'
});
$(div).addClass("Copyof" + name);
i++;
$('#boxContain').append(div);
if (div.getAttribute('name') == null) {
} else {
var p = document.createElement("p");
$(p).text(name);
$(p).attr('id', "Copyof" + name);
$(p).attr('class', name);
$(p).addClass('lbl');
$(p).addClass($(div).attr('id'));
$("#existingLbl").append(p);
}
}
});
}
$(div).attr('onclick', 'getElem(this); ');
HTML:
<form name="imageLblForm" method="post" id="imageLblForm" enctype="multipart/form-data" runat="server" action="#">
Sign out
<h4 id="errorMessage"></h4>
<section name="nav" class="nav">
<ul>
<li><input type="file" id="my_file" name="file1" onchange="" accept=".bmp,.jpg, .png, image/jpg, image/bmp, image/png" style="display:none" multiple /><input type="button" id="openBtn" class="openBtn" value="Open" onclick="document.getElementById('my_file').click();" /></li>
<li><input type="submit" value="Save" id="save" onclick="document.getElementById('hiddenLink').click(); return false; "><a onclick="document.execCommand('SaveAs','true','<?php if(isset($_FILES['file1'])){echo pathinfo($_FILES['file1']['name'], PATHINFO_FILENAME);}?>.xml');" id="hiddenLink">Save</a></li>
<li>
<hr />
</li>
<li><button onclick="createBox(); return false;" id="createBoxBtn">Create Rect Box</button></li>
<li><button onclick="addBox(); return false;" id="duplicateBox">Duplicate Rect Box</button></li>
<li><button onclick="deleteDiv(); return false;" id="deleteBox">Delete Rect Box</button></li>
<li><button id="zoomInBtn" onclick="return false;">Zoom In</button></li>
<li><button id="zoomOutBtn" onclick="return false;">Zoom Out</button></li>
</ul>
</section>
<section name="canvas" class="canvas" id="canvas">
<div id="boxContain"></div>
<div class="imageContainer" id="imageContainer">
</div>
</section>
<section id="rightPanel" name="rightPanel" class="rightPanel">
<div class="label" name="label" id="label">
<p id="sectionLbl">Box Labels</p>
<button id="editLblBtn" class="lbls" onclick="return false;">Change Label</button>
<hr />
<div id="existingLbl"></div>
<div id="lblList" class="modal">
<div class="modal-content">
<select id="labels">
<option disabled selected value> -- select a label -- </option>
<?php
$file_lines = file('lbls/predefined_classes.txt');
foreach($file_lines as $line){
?>
<option value="<?php echo $line; ?>">
<?php echo $line; ?>
</option>
<?php
}
?>
</select>
<span class="close">&cross;</span>
<input type="button" onclick="return false;" id="submitLbl" value="Select" />
<input type="button" onclick="return false;" id="editLbl" value="Edit" />
</div>
</div>
</div>
<div class="files" name="files" id="files">
<p>File List</p>
</div>
</section>
</form>
I HAVE TRIED:
$('#boxContain').on('click', function (event) {
var dupBtn = document.getElementById('duplicateBox');
var selBox = event.target;
var name = $(selBox).attr('name');
$(dupBtn).on('click', function () {
var check = document.getElementById("box0");
if (check === null || $(check).attr('name') == null) {
$(document.getElementById('errorMessage')).text("Please create a box and label it first");
document.getElementById('errorMessage').style.display = 'block';
alert("Please create a box and label it first");
} else {
document.getElementById('errorMessage').style.display = 'none';
document.getElementById("save").style.pointerEvents = ("auto");
var div = document.createElement('div');
$(div).attr('id', 'box' + i);
$(div).attr('class', 'box');
$(div).attr('name', name);
div.style.width = event.target.style.width;
div.style.height = event.target.style.height;
div.style.border = event.target.style.border;
div.style.background = event.target.style.background;
$(div).draggable({
containment: "#canvas"
});
$(div).resizable({
handles: 'ne, se, sw, nw'
});
$(div).addClass("Copyof" + name);
i++;
$('#boxContain').append(div);
if (div.getAttribute('name') == null) {
} else {
var p = document.createElement("p");
$(p).text(name);
$(p).attr('id', "Copyof" + name);
$(p).attr('class', name);
$(p).addClass('lbl');
$(p).addClass($(div).attr('id'));
$("#existingLbl").append(p);
}
}
}); //end of dupBtn onclick
}); //end of boxContain onclick
The codes are like this.When user creates a box,it will have a onclick attribute which calls the getElem() function.In this function,when the user clicks Duplicate Box button,the selected box will be duplicated and only ONE box should appear.But i keep having multiple boxes appearing.Please help me..Thank you.

Is LocalStorage variable exists: if statement does not work after element reloading (page is reloading after submiting reloaded form)

Please help to fix an algorithm and prevent reloading after clicking submit:
my website has to check, does user ever entered a nickname. If he did, then website have to show his name, if did not, then ask to type it. If the user decided to change it, he will click "reset username".
After clicking "reset" user has to submit twice his name (after first click on "Set" total page is reloading, and after second click it is reloading only one element). Please help to fix it - user has to submit it only once.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var formNewName = '<form id="new-task"> <input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text"> <input id="submitname" type="submit" value="Set new name1"> </form>';
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#setnewname').onsubmit = () => {
var newname;
localStorage.setItem('localN', newname);
document.querySelector('#nickName').innerHTML = formNewName;
// Stop form from submitting
return false;
};
});
// Checking does user entered his name
if ( !localStorage.getItem('localN') || localStorage.getItem('localN')=="undefined" )
{ var nick;
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#nickName').innerHTML = formNewName;
document.querySelector('#new-task').onsubmit = () => {
nick = document.querySelector('#nickN').value;
localStorage.setItem('localN', nick);
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>';
// Stop form from submitting
return false;
};
});
}
else
{
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>';
});
}
</script>
</head>
<body>
<div id = "nickName"></div>
<div id = "newname">
<br>
<form id="setnewname">
<input id="submitreset" type="submit" value="Reset nick name">
</form>
</div>
</body>
Update: event.preventDefault(); and event.stopPropagation(); does not helps to solve the problem.
Sorry for late reply if you are still having it, i couldn't see where you are taking the value from user in your code there's no input field where user can type so i'll add that and then on id submitreset you'll do this:
i work with jquery most so the syntax for that will be
// HTML CODE TO ADD
<input type="text" name="entername" id="entername">
// than in jquery for the submit button you already have
$(document).on("click","#submitreset",function(e){
e.preventDefaults();
var name = $(this).val();
// you can print the value in the div with this id
$("#nickName").html(name);
});
In a Russian language branch of StackOverflow I had received an answer (https://ru.stackoverflow.com/a/901260/291735):
HTML
<div id = "nickName">
<form id="new-task">
<input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text">
<input id="submitname" type="submit" value="Set new name1"> </form>
</div>
<div id = "newname">
<br>
<form id="setnewname">
<input id="submitreset" type="submit" value="Reset nick name">
</form>
</div>
JavaScript
var setName = document.getElementById('submitname');
var reset = document.getElementById('submitreset');
var nickN = document.getElementById('nickN');
document.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('localN')!== null){
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>'
}
})
setName.addEventListener('click', function(){
var newName = document.getElementById('nickN').value;
localStorage.setItem('localN', newName);
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>'
})
reset.addEventListener('click', function(){
delete localStorage['localN'];
document.querySelector('#nickName').innerHTML = '<input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text"> <input id="submitname" type="submit" value="Set new name1">'
});

determine the membership of the list

In the text field inputAddLabel some character is entered. When you click the Add tag button, the eventpushLabel ()is triggered. However, not every symbol should be added, but only one that is contained in listAlphabet. That is, a check must be carried out on the belonging of the added label to the alphabet.
function pushAlphabet() {
var alph = document.getElementById("inputAddAlphabet").value;
if(alph.length == 1){
var li = document.createElement("li");
li.textContent = alph + " ";
document.getElementById("listAlphabet").appendChild(li);
} else { alert('error');}
}
function pushLabel() {
var label = document.getElementById("inputAddLabel").value;
console.log("label", label);
var li = document.createElement("li");
li.textContent = label + " ";
document.getElementById("listLabels").appendChild(li);
}
<div class="alphabet">
<form>
<input id="inputAddAlphabet" type="text">
<input type="button" value="add symbol" onclick="pushAlphabet()">
</form>
<ul id="listAlphabet"></ul>
</div>
<div class="labels">
<form>
<input type="text" id="inputAddLabel">
<input type="button" value="add label" onclick="pushLabel()">
</form>
<ul id="listLabels"></ul>
</div>
Keep track of the pushed symbols (alphabet) and use them to filter the label:
var allowedLabels = [];
function pushAlphabet() {
var alph = document.getElementById("inputAddAlphabet").value;
allowedLabels.push(alph);
var li = document.createElement("li");
li.textContent = alph + " ";
document.getElementById("listAlphabet").appendChild(li);
document.getElementById("inputAddAlphabet").value = "";
}
function pushLabel() {
var label = document.getElementById("inputAddLabel").value;
console.log("label", label);
if (allowedLabels.indexOf(label) >= 0) {
var li = document.createElement("li");
li.textContent = label + " ";
document.getElementById("listLabels").appendChild(li);
document.getElementById("inputAddLabel").value = "";
} else { alert('error');}
}
<div class="alphabet">
<form>
<input id="inputAddAlphabet" type="text">
<input type="button" value="add symbol" onclick="pushAlphabet()">
</form>
<ul id="listAlphabet"></ul>
</div>
<div class="labels">
<form>
<input type="text" id="inputAddLabel">
<input type="button" value="add label" onclick="pushLabel()">
</form>
<ul id="listLabels"></ul>
</div>

Submitting two Forms is possible? asp.net mvc

I have two forms in a single page, and both have a save button respectively.
Whenever I click the other button, I want the changes that I added on the other form to be saved as well.
This is my code:
<div id="contentMain">
#using (Html.BeginForm("ClientLocationSave", "Client", FormMethod.Post, new { id = "clientLocForm" }))
{
<input type="hidden" id="clientId" name="clientId" value="#ViewBag.ClientId" />
<input type="hidden" id="clientLocId" name="clientLocId" value="#clientLocId" />
<h2>
Client Location #pageAction</h2>
<div class="main">
<p>
<label for="txtName">
Name</label>
<span>
<input type="text" id="txtName" name="txtName" class="validate[required] inputLong" value="#clientLocName" />
</span>
</p>
<p>
<label for="txtAddress1">
Address 1</label>
<span>
<input type="text" id="txtAddress1" name="txtAddress1" class="validate[required] inputLong" value="#addressLine1" />
</span>
</p>
<p>
<label for="txtAddress2">
Address 2</label>
<span>
<input type="text" id="txtAddress2" name="txtAddress2" class="inputLong" value="#addressLine2" />
</span>
</p>
<p>
<label for="txtCity">
City</label>
<span>
<input type="text" id="txtCity" name="txtCity" class="validate[required] inputLong" value="#city" />
</span>
</p>
<p>
<label for="ddlState">
State</label>
<span>
#Html.DropDownList("ddlState", new SelectList(ViewBag.StateList, "ID", "Display_Value", state), "[Please Select]",
new Dictionary<string, object>
{
{"class","validate[required] inputLong"}
})
</span>
</p>
<p>
<label for="txtZipCode">
Zip Code</label>
<span>
<input type="text" id="txtZipCode" name="txtZipCode" class="validate[required,custom[onlyNumberSp],maxSize[20]] inputLong" value="#zipCode" />
</span>
</p>
</div>
<input type="submit" id="btnSave" class="styledButton" value="Save" />
}
<div class="main">
#using (Html.BeginForm("ClientLocationContactSave", "Client", FormMethod.Post, new { id = "contactForm" }))
{
<input type="hidden" id="clientId" name="clientId" value="#clientId" />
<input type="hidden" id="clientLoctContactId" name="clientLoctContactId" value="#clientLoctContactId" />
<input type="hidden" id="clienLocatId" name="clienLocatId" value="#clientLocId" />
<p>
<label for="ddlContact">
Contact Type</label>
<span>
#Html.DropDownList("ddlContact", new SelectList(ViewBag.ContactType, "ID", "Display_Value", contactTypeLookId), "[Please Select]",
new Dictionary<string, object>
{
{"class","validate[required] inputLong"}
})
</span>
</p>
<p>
<label for="txtValue">
Contact Value</label>
<span>
<input type="text" id="txtValue" name="txtValue" class="validate[required] inputLong"
value="" />
<p>
<label for="chkSaveIsPrimary">
Is Primary</label>
<input type="checkbox" name="chkSaveIsPrimary" id="chkSaveIsPrimary" value="true" checked="checked" />
</p>
</span>
</p>
<script type="text/javascript">
$(document).ready(function () {
var disableFields = $('#clienLocatId').val();
if (disableFields == 0) {
$('#disable').attr("hidden", false);
$('#txtValue').attr("disabled", true);
$('#ddlContact').attr("disabled", true);
$('#chkSaveIsPrimary').attr("disabled", true);
}
else {
$('#disable').attr("hidden", true);
$('#txtValue').attr("disabled", false);
$('#ddlContact').attr("disabled", false);
$('#chkSaveIsPrimary').attr("disabled", false);
}
});
</script>
<p>
<span>
<input type="submit" id="btnAddLocationContact" name="btnAddLocationContact" class="styledButton"
value="Add Contact" />
</span>
</p>
}
</div>
CONTROLLER:
public ActionResult ClientLocationSave(FormCollection formCollection)
{
String msg = String.Empty;
String newClientLocationId = String.Empty;
String clientId = formCollection["clientId"];
String clientLocId = formCollection["clientLocId"];
String locationName = formCollection["txtName"];
String address1 = formCollection["txtAddress1"];
String address2 = formCollection["txtAddress2"];
String city = formCollection["txtCity"];
String state = formCollection["ddlState"];
String zipCode = formCollection["txtZipCode"];
Client_Location clientLoc = new Client_Location();
try
{
if (String.IsNullOrWhiteSpace(clientLocId) || clientLocId == "0")
{
clientLoc.ClientID = Convert.ToInt32(clientId);
clientLoc.Name = locationName.Trim();
clientLoc.Address_Line1 = address1;
clientLoc.Address_Line2 = address2;
clientLoc.City = city;
clientLoc.State_LookID = Convert.ToInt32(state);
clientLoc.ZipCode = zipCode;
clientLoc.DateCreated = DateTime.UtcNow;
clientLoc.DateModified = DateTime.UtcNow;
clientLoc.CreatedBy = User.Identity.Name;
clientLoc.ModifiedBy = User.Identity.Name;
db.Client_Location.Add(clientLoc);
}
else
{
int id = Convert.ToInt32(clientLocId);
clientLoc = (from a in db.Client_Location
where a.ID == id
select a).SingleOrDefault();
clientLoc.Name = locationName.Trim();
clientLoc.Address_Line1 = address1;
clientLoc.Address_Line2 = address2;
clientLoc.City = city;
clientLoc.State_LookID = Convert.ToInt32(state);
clientLoc.ZipCode = zipCode;
clientLoc.DateModified = DateTime.UtcNow;
clientLoc.ModifiedBy = User.Identity.Name;
}
}
catch (Exception)
{
msg = "Failed to save";
}
db.SaveChanges();
if (String.IsNullOrWhiteSpace((msg)))
{ TempData["message"] = "Client Location Saved Successfully."; }
else if (msg != "")
{ TempData["message"] = msg; }
newClientLocationId = clientLoc.ID.ToString();
return RedirectToAction("ClientLocationDetails", new { clientId = clientId, clientLocId = newClientLocationId });
}
public ActionResult ClientLocationContactSave(FormCollection formCollection)
{
String msg = String.Empty;
String clientId = formCollection["clientId"];
String clientLoctContactId = formCollection["clientLoctContactId"];
String clienLocatId = formCollection["clienLocatId"];
bool isPrimary = Convert.ToBoolean(formCollection["chkSaveIsPrimary"]);
String value = formCollection["txtValue"];
String contactTypeLookId = formCollection["ddlContact"];
Client_Location_Contact clientLoc = new Client_Location_Contact();
try
{
if (String.IsNullOrWhiteSpace(clientLoctContactId) || clientLoctContactId == "0")
{
clientLoc.Client_LocationID = Convert.ToInt32(clienLocatId);
clientLoc.Value = value.Trim();
clientLoc.IsPrimary = isPrimary;
clientLoc.ContactType_LookID = Convert.ToInt32(contactTypeLookId);
clientLoc.DateCreated = DateTime.UtcNow;
clientLoc.DateModified = DateTime.UtcNow;
clientLoc.CreatedBy = User.Identity.Name;
clientLoc.ModifiedBy = User.Identity.Name;
db.Client_Location_Contact.Add(clientLoc);
}
else
{
int id = Convert.ToInt32(clientLoctContactId);
clientLoc = (from a in db.Client_Location_Contact
where a.ID == id
select a).SingleOrDefault();
clientLoc.Value = value.Trim();
clientLoc.IsPrimary = isPrimary;
clientLoc.ContactType_LookID = Convert.ToInt32(contactTypeLookId);
clientLoc.DateModified = DateTime.UtcNow;
clientLoc.ModifiedBy = User.Identity.Name;
}
}
catch (Exception)
{
msg = "Failed to save";
}
db.SaveChanges();
if (String.IsNullOrWhiteSpace((msg)))
{ TempData["message"] = "Contact Saved Successfully."; }
else if (msg != "")
{ TempData["message"] = msg; }
ViewBag.clientLoctContactId = clientLoctContactId;
ViewBag.clienLocatId = clienLocatId;
return RedirectToAction("ClientLocationDetails", new { clientLocId = clienLocatId, clientId = clientId });
}
Can this be done with jQuery, and if yes - how?
Lets reword your question a little into something more abstract to help you:
You have two paper forms that need to be signed and given to your manager. One has to be given to Fred in HR, another to Wilma in Sales on the other side of the building.
Can you leave your desk and get both signed at once? Of course not. You need to pick one to do first and then go to the second one before finally arriving at your manager with both forms signed.
The same is true for your page, you can bundle it all into one form and submit it to the server, handle the first part, then get some other code to handle the second part, then return the result to the user.
While there is some fancy trickery you can use to get around this, you need to ask yourself why you would want to. If you always save both forms then why bother having two?

Categories

Resources