I need to send model parameter from div to script. This is my not working .cshtml file
#model List<Dialog>
#foreach (Dialog dialog in Model)
{
<div onclick="SelectDialog(#dialog)"></div>
}
<script>
function SelectDialog(dialog) {
//work with dialog
}
</script>
How can I send current dialog from view to script?
When addressing a model in the first line you should:
Index.cshtml
#model IEnumerable<YourProject.Models.Dialog>
or
#model YourProject.Models.Dialog
col1, col2 and col3 are your class objects
Class.cs
namespace YourProject.Models
{
public class Dialog {
[Key]
public int id { get; set; }
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
}
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
List<Dialog> all = new List<Dialog>();
...
return View(all);
}
}
Instead of Dialog object, can you achieve the desired functionality by passing parameters to SelectDialog? For example:
Instead of
function SelectDialog(Dialog d)
{
if (d.id == 1)
alert('first id');
else
alert('not first');
}
write:
function SelectDialog(int d)
{
if (d == 1)
alert('first id');
else
alert('not first');
}
Related
I'm working on an online attendance portal, In which I've set a condition in a controller that users can't mark attendance twice a day. They are only allowed to mark attendance once per day. So I want to show a message on the view page "Create" that "Attendance is already marked" if an employee is marking the attendance a second time on the same date. I've set an alert message but I want to show a message on the view page from where the employee is marking the attendance. I've searched for it a lot but can't find any better one.
Here's my Controller Code
[Authorize]
public ActionResult Create()
{
Employee employee = JsonConvert.DeserializeObject<Employee>(User.Identity.Name);
return View(new Attendance() { Emp_Id = employee.Emp_Id });
}
[HttpPost]
public ActionResult Create(Attendance attendance)
{
if (ModelState.IsValid)
{
try
{
var attdate = attendance.Date;
var nextdate = attdate.AddDays(1);
var id = Convert.ToInt32(Session["UserID"]);
var isExist = db.Attendance.FirstOrDefault(i => i.Emp_Id == id && i.Date == attdate && i.Date < nextdate);
if (isExist != null)
{
//Here i set the alert but i want to show message on view page.
return Content("<script language='javascript' type='text/javascript'>alert('Your Attendance is Already Marked');</script>");
}
else
{
//var res = tempDate.Date;
db.Attendance.Add(attendance);
db.SaveChanges();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.Message);
}
}
return RedirectToAction("Index", "Attendance");
}
Controller:
if (isExist != null)
{
TempData["Msg"] = "Your Attendance is Already Marked'"
}
View:
<body>
#if (TempData["Msg"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert(#TempData["Msg"]);
};
</script>
}
</body>
To display my message, I do this:
Model:
public class Alert
{
public const string TempDataKey = "TempDataAlerts";
public string AlertStyle { get; set; }
public string Message { get; set; }
public bool Dismissible { get; set; }
}
public class AlertStyle
{
public const string Success = "success";
public const string Information = "info";
public const string Warning = "warning";
public const string Danger = "danger";
}
My BaseController:
public class BaseController: Controller
{
public void Success(string message, bool dismissible = false)
{
AddAlert(AlertStyle.Success, message, dismissible);
}
public void Information(string message, bool dismissible = false)
{
AddAlert(AlertStyle.Information, message, dismissible);
}
public void Warning(string message, bool dismissible = false)
{
AddAlert(AlertStyle.Warning, message, dismissible);
}
public void Danger(string message, bool dismissible = false)
{
AddAlert(AlertStyle.Danger, message, dismissible);
}
private void AddAlert(string alertStyle, string message, bool dismissible)
{
var alerts = TempData.ContainsKey(Alert.TempDataKey)
? (List<Alert>)TempData[Alert.TempDataKey]
: new List<Alert>();
alerts.Add(new Alert
{
AlertStyle = alertStyle,
Message = message,
Dismissible = dismissible
});
TempData[Alert.TempDataKey] = alerts;
}
}
And in any controller I need is enough:
public class PanelController : BaseController
{
public ActionResult Index()
{
Success($"Hello World!!!",true);
return View();
}
}
PartialView for alert or message
#{
var alerts = TempData.ContainsKey(Alert.TempDataKey)
? (List<Alert>)TempData[Alert.TempDataKey]
: new List<Alert>();
#*if (alerts.Any())
{
<hr />
}*#
foreach (var alert in alerts)
{
var dismissibleClass = alert.Dismissible ? "alert-dismissible" : null;
<div class="alert alert-#alert.AlertStyle #dismissibleClass">
#if (alert.Dismissible)
{
<button type="button" class="close pull-left" data-dismiss="alert" aria-hidden="true">×</button>
}
#Html.Raw(alert.Message)
</div>
}
}
Finally:
<div class="mt-alerts">
#{ Html.RenderPartial("_Alerts"); }
</div>
so I'm currently working on a forum-like project that involves users to be able to submit a post to a database and then for the post title to be displayed on a datatable. The hyperlink of title will re-direct the user to the postDisplay page based from the postId that is submitted through the url.
The project is an asp.net web-form that uses Entity Framework.
The following code is the Post.cs Class
public class Post
{
//The post ID
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int postId { get; set; }
// Foreign key to customer
public string Id { get; set; }
public string postTitle { get; set; }
public string postBody { get; set; }
public string postDepartment { get; set; }
public string postCategory { get; set; }
public bool postAnonymous { get; set; }
public int postLikes { get; set; }
public int postDislikes { get; set; }
public DateTime postDate { get; set; }
}
The code below is responsible for submitting the post to the db
protected void AddPost(object sender, EventArgs e)
{
ApplicationUserManager _userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = _userManager.FindByName<ApplicationUser, string>(HttpContext.Current.User.Identity.Name);
var department = "";
using (var _dbContext = new ApplicationDbContext())
{
department = _dbContext.Departments.FirstOrDefault(c => c.deptId == user.deptId).deptName;
}
Post newPost = new Post()
{
postTitle = inputTitle.Text,
postBody = inputBody.Text,
postCategory = inputCategory.SelectedValue,
postAnonymous = Convert.ToBoolean(Int32.Parse(inputAnonymous.SelectedValue)),
Id = user.Id,
postDepartment = department,
postDate = DateTime.Now,
};
using (var _dbContext = new ApplicationDbContext())
{
_dbContext.Posts.Add(newPost);
_dbContext.SaveChanges();
}
//Display success message and clear the form.
string message = "Your suggestion has been submitted successfully!";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
The code below is reponsible for creating the DataTable that views the post titles while hyperlinking the postId to the postDisplay Page
<div class="jumbotron">
<table class="display" id="postsTable">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br />
</div>
<asp:HiddenField id="deptName" runat="server"/>
<script type="text/javascript">
$(document).ready(function () {
$('#postsTable') .DataTable({
pageLength: "5",
ajax: {
url: "/api/posts/GetDatatables",
type: "GET",
dataType: "json",
dataSrc: ""
},
columns: [
{
render: function (data, type, row, meta) {
return '' + row.postTitle+'';
}
},
{data: "postCategory"},
{data: "postDate"},
]
});
});
</script>
Now for the final part where the error seems to stumble, the postDisplay page starts with
protected void Page_Load(object sender, EventArgs e)
{
int postId = int.Parse(Request.QueryString["postId"]);
}
According to the debugger, the postId is requested correctly and is parsed to an int, but when the value is then displayed as int postId, it doesn't actually carry the number with it in the url?
<-------------------------EDIT-------------------------->
The following error is displayed from the line of code above
"Input string was not in a correct format."
Any suggestions would be appreciated.
This is my front-end:
ImageButton Details = (ImageButton)e.Row.FindControl("iBtnDetails");//take lable id
String strApplication1 = Details.CommandArgument.ToString();
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes.Add("onClick", "SelectRow()");
This is my back-end:
<script type="text/javascript">
function SelectRow() {
var strApplication1 = '<%=strApplication1%>'
if (strApplication1 == "IT Application Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "IT Account Request")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Change Control Management")
{
window.open('http://.aspx', '_blank');
}
else if (strApplication1 == "Backup & Restore")
{
window.open('http://.aspx', '_blank');
}
}
</script>
I want to pass String Argument to javascript function, but I got error that strApplication1 doesn't exist in the current context.
You need to make strApplication1 a public property on your page class. Currently, it is just an internal variable.
Something like:
public partial class YourPage : System.Web.UI.Page
{
public string strApplication1 {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
//Your page logic
}
//Looks like you set the variable in an onDatabound or similar.
//So use this where you currently set the variable
strApplication1 = Details.CommandArgument.ToString();
}
I submit a form to take objects from database.
I need to add varbinary(MAX) type (image) column inside json string, and send it via WebMethod to Ajax to display in the page, with the rest of the properties of the object. So in the class its string type instead of byte[] type.
In the encoding part I receive Javascript runtime Error:
Unable to get property 'pingInterval' of undefiened null reference.
<form id="form1" runat="server">
Arrival:
<input type="text" id="txtArrival" />
departure:
<input type="text" id="txtDeparture" />
Nob:
<input type="text" id="txtNob" />
<input type="button" id="btnSubmit" value="Get Rooms" />
</form>
Class:
public int ID { get; set; }
public string RoomType { get; set; }
public string RoomNumber { get; set; }
public string RoomTitle { get; set; }
public decimal Price { get; set; }
public string ServiceName { get; set; }
public string Photo { get; set; }
Ajax:
$(document).ready(function () {
$(function () {
$("#btnSubmit").click(function () {
var arrival = $("#txtArrival").val();
var departure = $("#txtDeparture").val();
var nob = $("#txtNob").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm2.aspx/GetRooms",
data: "{'arrival':'" + arrival + "','departure':'" + departure + "','nob':'" + nob + "'}",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (result) {
alert("Error!");
}
});
});
});
});
WebMethod:
[WebMethod]
public static string GetRooms(string arrival, string departure, string nob)
{
string val = "";
DateTime d1 = Convert.ToDateTime(arrival);
DateTime d2 = Convert.ToDateTime(departure);
int noib=Convert.ToInt32(nob);
var jSerialize = new JavaScriptSerializer();
List<Room> lst = new List<Room>();
using (SqlConnection con = new SqlConnection("Server=.;Database=ResDB;Trusted_Connection=True;"))
{
using (SqlCommand cmd = new SqlCommand("roomsAvailable", con))
{
cmd.Parameters.AddWithValue("#arr", d1);
cmd.Parameters.AddWithValue("#dep", d2);
cmd.Parameters.AddWithValue("#nob", noib);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader sr = cmd.ExecuteReader(); ;
while (sr.Read())
{
Room r = new Room();
r.ID = Convert.ToInt32(sr["ID"]);
//objects..
if (sr["Photo"] != System.DBNull.Value)
{
byte[] p = (byte[])sr["Photo"];
r.Photo = Convert.ToBase64String(p);// error here
}
lst.Add(r);
val = jSerialize.Serialize(lst);
}
con.Close();
}
}
return val;
}
Error is in this statement in WebMethod:
r.Photo = Convert.ToBase64String(p);
After changing JQuery hosted file to newer version,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
Error disappeared!
I am trying to create a demo of Group Chat using reverse ajax in Spring. I am using Spring 3.2.0.RELEASE version.
I am using DeferredResult to perform reverse ajax in my controller. Following is the snippet of my Controller class.
#Autowired
private AsyncRepository asyncRepository;
Map<Integer, List<DeferredResult<String>>> watchers = new ConcurrentHashMap<Integer, List<DeferredResult<String>>>();
#RequestMapping(value="/asyncRequest/getMessages/{id}", method=RequestMethod.GET)
#ResponseBody
public DeferredResult<String> getMessages(final #PathVariable("id") Integer id){
final DeferredResult<String> deferredResult = new DeferredResult<String>(null, Collections.emptyList());
if(watchers.containsKey(id)) {
watchers.get(id).add(deferredResult);
} else {
watchers.put(id, new ArrayList<DeferredResult<String>>());
watchers.get(id).add(deferredResult);
}
deferredResult.onCompletion(new Runnable() {
#Override
public void run() {
watchers.get(id).remove(deferredResult);
}
});
return deferredResult;
}
#RequestMapping(value="/asyncRequest/setMessages/{id}/{message}", method=RequestMethod.GET)
#ResponseBody
public String setMessage(#PathVariable("id") Integer id, #PathVariable("message") String message) {
asyncRepository.setMessage(id, message);
return "";
}
#Scheduled(fixedRate=1000)
public void processQueues() {
for (Map.Entry<Integer, Queue<AsyncDataBean>> entry : asyncRepository.getAsyncBeans().entrySet()) {
while(entry != null && entry.getValue() != null && !entry.getValue().isEmpty()) {
AsyncDataBean asyncDataBean = entry.getValue().poll();
for (DeferredResult<String> deferredResult : watchers.get(asyncDataBean.getId())) {
deferredResult.setResult(asyncDataBean.getMessage());
}
}
}
}
And below is the Repository class which holds the Map of GroupID and its relevant messageQueue. And it also has the functions for getting and setting the messages for relevant group id.
#Repository
public class AsyncRepository {
private Map<Integer, Queue<AsyncDataBean>> asyncBeans = new ConcurrentHashMap<Integer, Queue<AsyncDataBean>>();
public String getMessages(Integer id) {
StringBuilder stringBuilder = new StringBuilder();
while (asyncBeans.get(id) != null && !asyncBeans.get(id).isEmpty()) {
stringBuilder.append(asyncBeans.get(id).poll().getMessage()).append("~");
}
return stringBuilder.toString();
}
public void setMessage(Integer id, String message) {
if(asyncBeans.containsKey(id)) {
asyncBeans.get(id).add(new AsyncDataBean(id, message));
} else {
Queue<AsyncDataBean> messageQueue = new ConcurrentLinkedQueue<AsyncDataBean>();
messageQueue.add(new AsyncDataBean(id, message));
asyncBeans.put(id, messageQueue);
}
}
public Map<Integer, Queue<AsyncDataBean>> getAsyncBeans() {
return asyncBeans;
}
public void setAsyncBeans(Map<Integer, Queue<AsyncDataBean>> asyncBeans) {
this.asyncBeans = asyncBeans;
}
}
And below is the data bean I am using to store each message with its group id.
public class AsyncDataBean {
private Integer id;
private String message;
public AsyncDataBean() {
}
public AsyncDataBean(int id, String message) {
this.setId(id);
this.setMessage(message);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And then comes the jsp page for group chat. which looks like below.
<script type="text/javascript">
var messagesWaiting = false;
function getMessages(){
if(!messagesWaiting){
$.ajax({ url: "${pageContext.servletContext.contextPath}/asyncRequest/getMessages/${id}",
dataType:"text",
success: function(data,textStatus,jqXHR) {
if(textStatus == 'success'){
messagesWaiting = false;
var arr = data.split("~");
for(var i=0; i<arr.length; i++)
{
try
{
if(arr[i] != '') {
$("#txtaMessages").val($("#txtaMessages").val() + "\n\n" + arr[i]);
document.getElementById("txtaMessages").scrollTop = document.getElementById("txtaMessages").scrollHeight;
}
}
catch(e){
alert(e.message);
}
}
}
},
complete: function(j) {
},
error: function(xhr) {
}
});
messagesWaiting = true;
}
}
setInterval(getMessages, 1000);
getMessages();
function sendMessage() {
var xmlhttp1 = new XMLHttpRequest();
xmlhttp1.open("GET", '${pageContext.servletContext.contextPath}/asyncRequest/setMessages/${id}/' + $("#txtMessage").val(), true);
xmlhttp1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp1.send();
$("#txtMessage").val("");
$("#txtMessage").focus();
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<table>
<tr>
<td>Messages :: </td>
<td>
<textarea cols="100" rows="10" id="txtaMessages"></textarea>
</td>
</tr>
<tr>
<td>Send Message :: </td>
<td><input type="text" id="txtMessage"/></td>
</tr>
<tr>
<td><input type="button" value="Send" onclick="sendMessage();"/></td>
</tr>
</table>
</body>
</html>
That is what I have coded till now to get this working. And everything is working finw in FF and Chrome. But in IE it is not working as expected. The request is never gets hold on the server and it always gets executed every second as configured in the javascript code. And it always returns the same result as previous. I have tried to use several other methods to send ajax request for IE but its not working. Can anyone get it working for me?
Since everything works fine in FF and Chrome, I suspect the problem is with javascript code to send the request to get messages.
Please help me.
Thanks in advance.
This is very very frustrating.
To get this thing work properly in IE I need to set cache:false attribute in the ajax request I am creating with jquery for getMessages. Otherwise IE will not hold the request in pending status and always returns back with the old response text.
Its a very big issue with IE. I hope no one face the problem again or finds this answer as early as possible.
:)