How to update database in entity framework using javascript? - javascript

Working on CRUD in webforms using entity framework. I wrote this aspx.cs file and crud is working fine. Now, I want to update department of employee only if experience>3 in javascript. But, unable to know how to proceed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ProjectEMS
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
EM em = new EM();
em.Empid = tbempid.Text;
em.Name = tbname.Text;
em.Department = tbdepartment.Text;
em.Experience = tbexperience.Text;
em.DOB = tbdob.Text;
em.DOJ = tbdoj.Text;
ProjectEMSEntities1 db = new ProjectEMSEntities1();
db.EMS.Add(em);
db.SaveChanges();
lblsuccess.Text = "Data added successfully!";
}
}
}

Related

Trying to post a list collection to the controller with ajax

I'm trying to post a list collection to the controller with a full page post back to the server. The data from the client side is written with JavaScript / jQuery and the server code is written in C# using ASP.Net MVC.
I'm not sure what the issue is because when the ItemCheck method is hit with a breakpoint on the first curly brace after the method name but the model object Items property is null even though it's in the form data mentioned further below.
The code below is simplified for ease and is not working.
Input hidden field in the view where the JavaScript adds an item to it each time add button is pressed.
#model UI.ViewModels.ItemResource
#Html.HiddenFor(model => model.Items, new { #id = "Items" })
<button class="btn-default btn" id="AddItem" name="AddItem" type="button" disabled>Add</button>
JavaScript
var items = [];
// This code only adds an item to the items collection input hidden
// field for a full page post back to the server.
var addItemToList = function () {
var item = {
ItemDate: $(date).val(),
ItemAmount: $(amount).val()
};
items.push(item);
$("#Items").val( JSON.stringify(items));
};
Controller
public ActionResult ItemCheck(ItemViewModel model)
{
if (result.IsValid)
{
model.Items = _anotherViewModel.Items;
_anotherViewModel.Items= null;
model.IsValid = _itemService.Save(model, _Itemhelper.GetUserId());
}
else
{
//Validation here
}
return View(model);
}
ViewModels
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace UI.ViewModels.ItemResource
{
public class ItemsViewModel
{
public ItemsViewModel()
{
Items = new List<ItemViewModel>();
}
[JsonBindable]
public List<ItemViewModel> Items { get; set; }
}
public class ItemViewModel
{
public DateTime ItemDate { get; set; }
public decimal ItemAmount { get; set; }
}
}
FormData
Items: [{"ItemDate":"2020-06-05","ItemAmount":"2267"}]

asp.net: javascript function works when called from button click event, not when called from subscription event from redis

i'm using the same js script call in both scenarios... one it is called from a button_click event and it works properly (changes the label text) as per below...
public void Test_OnClientClick(object sender, EventArgs e)
{
Console.WriteLine("test");
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
When it is called from an event raised by a redis subscription, the same call does not work...
public void Page_Load(object sender, EventArgs e)
{
// Establish connection
redisConn = ConnectionMultiplexer.Connect(redisIP);
rbsub = redisConn.GetSubscriber();
rbsub.Subscribe(ServerRedisChannel).OnMessage(channelMessage => {
MessageHandler(channelMessage.Message.ToString());
});
}
public void MessageHandler(string cm)
{
try
{
//Test_OnClientClick(null, null);
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
catch (Exception e)
{
var x = e;
}
}
I confirm it reaches the ClientScript call in MessageHandler with a breakpoint but it never reaches the debugger in the js script.
Full code below:
Default.aspx
<%# Page Title="Home Page" Async="true" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForm._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function updateText(strData) {
debugger;
document.getElementById("<%=lblTest.ClientID%>").innerHTML = strData;
}
</script>
<div class="jumbotron">
<h1>redis test</h1>
<p><asp:Label ID="lblTest" runat="server" Text="redis output"></asp:Label></p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Test_OnClientClick"/>
<p>Learn more ยป</p>
</div>
</asp:Content>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StackExchange.Redis;
namespace WebForm
{
public partial class _Default : Page
{
ConnectionMultiplexer redisConn;
ISubscriber rbsub;
public const string redisIP = "gptdevnj01:6379";
public const string ServerRedisChannel = "ac";
public const int redisDB = 7;
public void Page_Load(object sender, EventArgs e)
{
// Establish connection
redisConn = ConnectionMultiplexer.Connect(redisIP);
rbsub = redisConn.GetSubscriber();
rbsub.Subscribe(ServerRedisChannel).OnMessage(channelMessage => {
MessageHandler(channelMessage.Message.ToString());
});
}
public void MessageHandler(string cm)
{
try
{
//Test_OnClientClick(null, null);
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
catch (Exception e)
{
var x = e;
}
}
public void Test_OnClientClick(object sender, EventArgs e)
{
Console.WriteLine("test");
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
}
}
So i suppose the question boils down to calling a js script from a button_click event differs from when it is called from a subscription (or async) event?
Response to a button click happens within ASP.NET Page Lifecycle, whereas handling of an asynchronous message from a Redis subscription will most likely:
happen completely outside of that lifecycle, and
in a completely different thread.
Unless you synchronize those threads somehow (one that handles the request and one that handles received messages) - your call to ClientScript.RegisterStartupScript will go to void, to wrong client or simply fail. Please note however that the nature of asynchronous operations may require a different approach from your side rather blocking a thread to wait for a message.

Pass JavaScript Value from Webview to Activity?Android

I followed this to Print in android (Thermal Printer)
This is My web-view Over there On-click It will Load My Android Activity Which is Out of Web-view...
For that I have Given this... to Open new activity from web-view..
public class Main_web extends AppCompatActivity {
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_m);
webView = (WebView) findViewById(R.id.webm);
WebSettings set = webView.getSettings();
set.setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
final ProgressDialog progressBar = ProgressDialog.show(Main_web.this, "Please Wait", "Loading...");
webView.addJavascriptInterface(new WebAppInterface(this), "NewFUN");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient()
{
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webView.setWebChromeClient(new WebChromeClient());
String url = "www.google.com/m_app_eta.php";
//String url = "file:///android_asset/tex.html";
try {
if (URLUtil.isValidUrl(url)) {
webView.loadUrl(url);
} else {
//do something
}
} catch (Exception e) {
//do something
}
}
//Class to be injected in Web page
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void Print() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure you want to leave to next screen?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent chnIntent = new Intent(Main_web.this, Print_activity.class);
startActivity(chnIntent);
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
}
Now My printer Activity is working Fine So here I want to pass a Value On click Button Which Opens Printer... But can Any one suggest me How to Receive same value in android Activity not in web-view...
All I need is In my web-view when I click on the Button its loading Android Activity Along with that I want to Pass A string value to new Activity
Why Should I pass Value means In that I have a Url so I can Print with that URL
Here JS value is different form current URL
Update
I followed this But its Inside the Web-view I want same at Outside the web-view...
Means When I click on the web-view Its opening android activity with the same its should pass a value to my activity not the web-view
Update 1
I followed #Sujal Mandal answer But I dont Know How to use that Value In next activity Can any one suggest me... on this kind... in next activity It may in System.out.println or text-view or any other string So I can use can Any one suggest How to Use the JavaScript Value in other activity outside the web-view..
HTML JS CODE
<script type="text/javascript">
function Pa(value) {
//value is the param received from onClick
NewFUN.Print(value); //call the android method with value param
}
</script>
<center>
<h3>Sample HTML</h3>
<div id="content">Click on Button To thermal print</div>
<div>
<input type="button" onClick="Pa('26997')" /><br/>
</div>
</center>
& change your android code to be like this
#JavascriptInterface
public void Print(final String stringFromWebView) {
//use stringFromWebView
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure you want to leave to next screen?");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent chnIntent = new Intent(Main_web.this, Print_activity.class);
chnIntent.putExtra("STRING_DATA", stringFromWebView);
startActivity(chnIntent);
}
});
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
In next activity receive the web JS response by using
String data = getIntent().getStringExtra("STRING_DATA");
at oncreate

Call codebehind function from javascript with parameter

I need call codebehind function with parameter which is instance of some Entity class from script tags in aspx page. Im created popup windows from kendo ui using kendotemplate and in this template i need my form with inputs and button used in code behind. Something like this http://demos.telerik.com/kendo-ui/grid/custom-command but when i add asp items to template tags not work for me.
My entity:
public class Person
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
public int Age { get; set; }
}
code behind function:
protected void btnAddPerson_Click(object sender, EventArgs e)
{
Person p= new Person();
// get values from three inputs
p.FirstName= personFirstName.Value;
p.LastName= personLastName.Value;
p.Age = Convert.ToInt32(personAge.Value);
...
}
i need in javascript something like this:
<script type="text/x-kendo-template" id="template">
<Asp:Input ...>
<Asp:Input ...>
<Asp:Input ...>
<Asp:Button ...>
</script>
and sorry for my english

How to assign value in $(document).ready from code behind

i'm developing a .net application using twitter bootstrap.
I'm trying to get data from .aspx.cs page to .aspx page.
Please find my code below:
strOblect.cs
public class strObject
{
public string Name { get; set; }
public string Description { get; set; }
}
.aspx.cs page:
public List<strObject> stringList = new List<strObject>();
protected void Page_Load(object sender, EventArgs e)
{
strObject ObjOne=new strObject();
ObjOne.Name="One";
ObjOne.Description ="One";
stringList.Add(ObjOne);
strObject ObjTwo=new strObject();
ObjTwo.Name="Two";
ObjTwo.Description ="Two";
stringList.Add(ObjTwo);
strObject ObjThree=new strObject();
ObjThree.Name="Three";
ObjThree.Description ="Three";
stringList.Add(ObjThree);
}
.aspx:
<asp:Panel ID="pnlData" runat="server" style="background-color:White;">
<script type="text/javascript">
$(document).ready(function () {
var valueAssigned=stringList;
});
</script>
</asp:Panel>
I'm unable to get stringList value in $(document).ready.
Please help me out to get the value.
It appears that your stringList is actually a collection of objects. In order to use it in JavaScript as such, you'll need to serialize it to a javascript object.
var valueAssigned=<%=new JavaScriptSerializer().Serialize(stringList)%>;
So that you can wind up with the following:
var valueAssigned= [{Name: "Foo", Description: "Bar"}, {...}];
Edit
JavaScriptSerializer is in System.Web.Script.Serialization - you'll either need to add this below at the top of your <%# Page
<%# Import Namespace="System.Web.Script.Serialization" %>
or specify the FQ name
var valueAssigned=<%=new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(stringList)%>;
StuartLC's answer will be enough.JSON is very good option for that purpose. Other option can be to register client script in aspx.cs. Here is another SO question regarding that
How do I pass data from c# to jquery/javascript?

Categories