How I tried to refresh div of the webpage? - c#

When I tried to refresh my page I can do it with this code;
$(document).ready(function () {
var interval = 500;
var refresh = function () {
$.ajax({
url: "https://localhost:44399/area/areadetail/#ViewBag.i",
cache: false,
success: function (html) {
$('.yika').html(html);
setTimeout(function () {
refresh();
}, interval);
}
});
};
refresh();
});
but my web page seems as;
How can I fix this situation in my code?

I will refresh the part of the page for you
step 1. add this class
public class JsonData
{
public string HtmlMsg { get; set; }
public string HtmlBody { get; set; }
public bool Success { get; set; }
}
step 2. then add class ViewHelper.cs
public static class ViewHelper
{
public static string RenderPartialToString(this ControllerBase controller)
{
return RenderViewToString(controller);
}
public static string RenderPartialToString(this ControllerBase controller, string partialViewName)
{
IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
return RenderViewToString(controller, view);
}
public static string RenderPartialToString(this ControllerBase controller, string partialViewName, object model)
{
IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
return RenderViewToString(controller, view, model);
}
}
step 3. add your PartialView and Put the part you want to refresh in PartialView exapmle:_MyDiv
<div class="col-level1-20">
<div class="row-new shadow-slider-list background-white border-r-1-ddd border-t-ddd">
refresh div
</div>
</div>
step 4. Your Action in Controller
public ActionResult areadetail(int id)
{
//............
return Json(new JsonData()
{
HtmlMsg = "OK",
HtmlBody = this.RenderPartialToString("_MyDiv"),
Success = true,
});
}
step 5. add PartialView in View
#{
ViewBag.Title = "TestPartialView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<section class="row-new margin-t-10">
<div class="row-new">
<div class="container style-direction-rtl">
<span class="style-font-16-sb color-black">Test PartialView</span>
</div>
<div class="container style-direction-rtl" id="yika">
#Html.Partial("_MyDiv")
</div>
</div>
</section>
step 6. Finally add script
$(document).ready(function () {
var interval = 500;
var refresh = function () {
$.ajax({
url: "https://localhost:44399/area/areadetail/#ViewBag.i",
cache: false,
success: function (result) {
if(result.Success)
{
$('#yika').html(result.HtmlBody);
}
else
{
alert('failed');
}
}
error: function () {
alert('error');
}
});
};
});

Related

How would i get the data from each event from a jsonResult with full calendar

I'm attempting to get event data (Title, date,etc) for an event when clicked but I can't figure out a way to do it since I add the data through the JSON result and full calendar javascript. If I cant, is there a better way to allow the backend razorpage to send data to the full calendar javascript?
backend
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using DynaHealth.Models;
using Microsoft.AspNetCore.Http;
namespace TeleHealthB.Pages
{
public class CalendarModel : PageModel
{
// public IndexModel(TeleHealthB.Models.HealthProjectContext context)
//{
// healthProject = context;
//}
[BindProperty]
public string Title { get; set; }
[BindProperty]
public string Doc { get; set; }
[BindProperty]
public string Pat { get; set; }
[BindProperty]
public string dec { get; set; }
[BindProperty]
public DateTime date { get; set; }
[BindProperty]
public JsonResult result { get; set; }
public string today = DateTime.Today.ToString();
public void OnGet()
{
// result = (JsonResult)OnGetEvents();
}
public class eventShow
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
//public string description { get; set; }
// public string patient { get; set; }
// public string doctor { get; set; }
}
private DynaHealth2Context db;
public CalendarModel(DynaHealth2Context _db)
{
db = _db;
}
public IActionResult OnGetEvents()
{
List<eventShow> events = new List<eventShow>();
eventShow show = new eventShow();
try
{
string x = HttpContext.Session.GetString("Username");
using (var context = new DynaHealth2Context())
{
var query = from st in context.Appointments
where st.PatientEmail == x.Trim() || st.ProviderEmail == x.Trim()
select st;
// foreach (var item in query.ToList())
// {
// show.id = item.Id;
// show.title = item.Title;
// show.description = item.Description;
// show.start = item.Start.ToString("MM/dd/yyyy");
//show.end = item.End.ToString("MM/dd/yyyy");
// events.Add(show);
// }
return new JsonResult(query.ToList());
}
}
catch { return null; }
}
public IActionResult OnGetADDEvent(string sub)
{
// using (var context = new HealthProjectContext())
{
try
{
//context.Schedules.Add(schedule);
return null;
}
catch { return null; };
}
}
// public onPost()
// {
// RedirectToPage("./Meeting");
// }
public IActionResult OnPostRemoveEvent(string sub)
{
// using (var context = new HealthProjectContext())
{
try
{
// context.Schedules.Add(schedule);
return null;
}
catch { return null; };
}
}
}
}
frontend
#model TeleHealthB.Pages.CalendarModel
#{
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Calendar</title>
<link href='~/lib/TestCalendar/main.css' rel='stylesheet' />
<script src='~/lib/TestCalendar/main.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
initialDate: Date.now(),
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
select: function (arg) {
var title = prompt('Reasining For meeting:');
if (title) {
var tie = prompt('Time');
}
if (title) {
calendar.addEvent({
title: title,
start: arg.start,
Starttime: tie,
end: arg.end,
EndTime: arg.EndTime
})
}
calendar.unselect()
},
eventClick: function (event, jsEvent, view) {
window.open("/Meeting", "_blank");
return false
},
editable: false,
dayMaxEvents: true, // allow "more" link when too many events
events: "/calendar?handler=events"
});
calendar.render();
});
</script>
<style>
#calendar {
max-width: 1100px;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>Schedule View</h1>
<div id='calendar'></div>
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="false">x</span>
<span class="sr-only">Close</span>
</button>
<h4 id="modalTItle" class="modal-title"> </h4>
</div>
<div id="modalBody" class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" name="del" class="btn btn-default" id="eventURL">Delete</button>
<a class="btn btn-primary" id="eventURL" target="_blank">Schedule</a>
</div>
</div>
</div>
</div>
</body>
</html>
}
If you want to get the event in the backend,you can do following change:
You can use code var events = calendar.getEvents(); to get all the events,and then push the property you want in the array,the pass the arry to the backend.
Frontend
//Add a button to get event:
<button id="GetEvent">Get Event</button>
//....
document.addEventListener('DOMContentLoaded', function () {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
initialDate: Date.now(),
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
select: function (arg) {
var title = prompt('Reasining For meeting:');
if (title) {
var tie = prompt('Time');
}
if (title) {
calendar.addEvent({
title: title,
start: arg.start,
Starttime: tie,
end: arg.end,
EndTime: arg.EndTime
})
}
calendar.unselect()
},
eventClick: function (event, jsEvent, view) {
window.open("/Meeting", "_blank");
return false
},
editable: false,
dayMaxEvents: true, // allow "more" link when too many events
events: "/calendar?handler=events"
});
calendar.render();
//add following
$("#GetEvent").click(function () {
var events = calendar.getEvents();
var e = [];
$.each(events, function (index, value) {
console.log(value.start);
console.log(index);
var start_time = value.start;
var end_time = value.end;
var id = parseInt(value.id);
var slot = {
start: start_time,
end: end_time,
id: id,
};
e.push(slot);
});
$.ajax({
url: '/test?handler=getevents',
contentType:"application/json",
data: JSON.stringify(e),
dataType: "json",
type: "POST",
});
});
});
Backend:
//add this line
[IgnoreAntiforgeryToken]
public class TestModel : PageModel
{
[BindProperty]
public string Title { get; set; }
[BindProperty]
public string Doc { get; set; }
[BindProperty]
public string Pat { get; set; }
[BindProperty]
public string dec { get; set; }
[BindProperty]
public DateTime date { get; set; }
//delete this line
//[BindProperty]
public JsonResult result { get; set; }
public string today = DateTime.Today.ToString();
public void OnGet()
{
JsonResult result = (JsonResult)OnGetEvents();
}
public class eventShow
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public IActionResult OnGetEvents()
{
}
public void OnPostGetEvents([FromBody]List<eventShow> model)
{
}
Test result:

Get infos of submit button after a foreach

I try to put some info into a new modal :
when I click on a button I want to open a new modal with good info of clicked pokemon.
I made controller :
public IActionResult Index()
{
#region ListeDesPokemons
var pokemonList = new List<PokemonModel>();
var Id = 1;
var Img = 1;
pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Bulbizarre", UsName = "Bulbasaur(us)", JpName = "フシギダネ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://www.pokemontrash.com/pokedex/images/sugimori/00" + Img++ + ".png" });
pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Herbizarre", UsName = "Ivysaur(us)", JpName = "フシギソウ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://www.pokemontrash.com/pokedex/images/sugimori/00" + Img++ + ".png" });
var model = new PokemonViewModel();
model.Pokemons = pokemonList;
return View(model);
I made a Viewmodel :
public List<PokemonModel> Pokemons { get; set; }
public List<PokeBallModel> PokeBalls { get; set; }
public List<PokemonStatutModel> PokemonStatuts { get; set; }
}
I made a Model :
public int Id { get; set; }
public string Name { get; set; }
public string UsName { get; set; }
public string JpName { get; set; }
public string Type1 { get; set; }
public string Type2 { get; set; }
public int Rate { get; set; }
public string Image { get; set; }
I made a view :
#foreach (var pokemon in Model.Pokemons){ #pokemon.Id,#pokemon.Name #pokemon.Image}
here a picture of the first modal on the back of the screen with all pokemon list (foreach)
and the second modal on the front of the screen with no info.
please help.
I think you don't need to use form and should use ajax, when user click the picture of pokemon, you call an ajax with the Id of this pokemon, and in the controller you search all infos of pokemon with Id, and success in ajax just add infomations to the modal dialog. Something like:
<img class="align-self-center" id="tailleImg" src="#pokemon.Image" alt="#pokemon.Name" onclick="getInfo(#pokemon.Id)" />
function getInfo(val)
{
$.ajax({
url: '/yourController/yourActionToGetInfo',
type: "POST",
dataType: "json",
data: { "pokeId": val},
success: function (data) {
$("#pokeId").val(data.Id);
}
})
}
ok
In my view, in my foreach I add :
#foreach (var pokemon in Model.Pokemons)
{
<div class="col">
<button data-pokemon-id="#pokemon.Id" type="submit" class="btn" onclick="getInfo();">
<div class="card text-center rounded-lg">
<div id="tailleCard" class="card-body">
<h5 id="cardTitle" class="card-title">n°#pokemon.Id <br /> #pokemon.Name</h5>
<img id="tailleImg" src="#pokemon.Image" alt="#pokemon.Name" />
</div>
</div>
</button>
</div>
}
# the end of the view I add : But the Request does not exist in the current context nedd help please.
<script>
function getInfo() {
$.post('#(Url.Action("PokemonDetails", "Pokedex", null, Request.Url.Scheme))?pokemonId=' +
$(this).data("pokemon-id"))
.done(function (response) {
$("#divContent").empty();
$("#divContent").html(response);
$("#divContent").html(response);
$('#pokemonDetailsModal').modal('show');
});
</script>
In the controller I add a :
public IActionResult PokemonDetails(int pokemonId)
{
var model = new PokemonDetails();
return PartialView("_PokemonDetails", model);
}
I also made a Partial view _ and a PokemonDetail Model
public class PokemonDetails
{
public string Name { get; set; }
}
What I try to do it's to take the data of the selected pokemon (with the button in the foreach) and put the data of the selected pokemon in New Modal.
OK i almost there ! cool
in the view
...
#foreach (var pokemon in Model.Pokemons)
{
<button type="submit" class="btn" onclick="getInfo(#pokemon.Id)">
<div class="card text-center rounded-lg">
<div id="tailleCard" class="card-body">
<h5 id="cardTitle" class="card-title">n°#pokemon.Id <br /> #pokemon.Name</h5>
<img id="tailleImg" src="#pokemon.Image" alt="#pokemon.Name" />
</div>
</div>
</button>
}
...
at the end of the view page :
<script>
function getInfo(val) {
event.preventDefault;
//debug log
console.log('Star getInfo()');
$.ajax({
url: '/Pokedex/PokemonDetails/',
type: 'POST',
dataType: "html",
data: { "PokemonId": val },
//data: json,
//contentType: 'application/json; charset=utf-8',
success: function (response) {
//debug log
console.log(val);
$("#pokemonDetails").html(response);
$('#pokemonDetails').modal('show');
}
})
}
</script>
in the controller :
[HttpPost]
public IActionResult PokemonDetails(int PokemonId)
{
int SelectedPokemonId = PokemonId;
TempData["SelectedPokemonId"] = SelectedPokemonId;
ToDoo : Get Info of the pokemon from the Id
return PartialView("_PokemonDetails");
}
How I can get the info of the selected pokemon from the selected Id???
https://i.stack.imgur.com/atajO.png
[HttpPost]
public IActionResult PokemonDetails(int PokemonId)
{
int SelectedPokemonId = PokemonId;
TempData["SelectedPokemonId"] = SelectedPokemonId;
ToDoo : Get Info of the pokemon from the Id
return PartialView("_PokemonDetails");
}
Do you have database ? if you have just call:
return (db.PokemonModel.FirstOrDefault(n=>n.Id == PokemonId));
and if you don't have use the list you use in action Index:
return pokemonList.FirstOrDefault(n=>n.Id == PokemonId));
and in sucess ajax:
success: function (response) {
$("#cardTitle").html("n°" + response.Id +"<br />" + response.Name");
$("#tailleImg").attr('src', response.Image);
$("#tailleImg").attr('name', response.Name);
$('#pokemonDetails').modal('show');
}

ASP MVC knockout json nested foreach data binding

Sorry if this particular question has been asked already, I have been through countless similar questions but none that seem to relate with my problem.
I am fairly new to MVC Web API's and working with JavaScript/knockout.
View model script - QuestionItems.js
var SectionModel = function (data) {
var self = this;
self.SectionName = ko.observable(data.SectionName);
self.SectionNumber = ko.observable(data.SectionNumber);
self.Questions = ko.observableArray();
};
var questionnaireViewModel = function () {
self.sections = ko.observableArray();
self.error = ko.observable();
var itemsUri = '/api/QuestionnaireItems/';
var sectionsUri = '/api/QuestionnaireSections/';
function ajaxHelper(uri, method, data) {
self.error('');
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllQuestions() {
ajaxHelper(itemsUri, 'GET').done(function (data) {
for (var s = 0; s < self.sections.length; s++) {
// find all the questions for this section
var sectionQuestions = data.filter(function (item) {
return item.SectionName == self.sections[s].SectionName;
});
// add the questions to each section
self.sections.Questions(sectionQuestions);
}
});
}
function getAllSections() {
ajaxHelper(sectionsUri, 'GET').done(function (data) {
// map each data item to a SectionModel and store that in your main viewModel
var sectionsTemp = data.map(function (item) {
return new SectionModel(item);
});
self.sections(sectionsTemp);
});
}
getAllSections();
getAllQuestions();
};
ko.applyBindings(questionnaireViewModel);
And my view - Index.cshtml
#section scripts {
#Scripts.Render("~/bundles/QuestionItems")
}
<div class="col-lg-12">
<h1 class="page-header">SQA</h1>
<ul class="list-unstyled" data-bind="foreach: sections">
<li>
<div class="panel panel-default">
<div class="panel-heading">
<div><strong data-bind="text: SectionNumber"></strong>. <strong data-bind="text: SectionName"></strong></div>
</div>
<div class="panel-body">
<ul data-bind="foreach: Questions">
<li>
<span data-bind="text: QuestionNumber"></span>. <span data-bind="text: QuestionName"></span>
</li>
</ul>
</div>
</div>
</li>
</ul>
</div>
In the database I have a QuestionnaireItems table which stores all question details and a foreign key to the sections table to retrieve each questions related section :
QuestionnaireItems
And a QuestionnaireSections table which holds each sections name and order number :
QuestionnaireSections
I have managed to get the sections displaying, however the questions are not. If I pull through just the questions without matching them to their correct sections they display. I'm assuming this is a problem with the way the condition is set up but I am at a complete loss as to how I can fix this.
I have also tested the controllers in Postman and all the correct data is pulling through.
QuestionItemList.cs (DTO):
public class QuestionItemList
{
public int Id { get; set; }
public int SectionNumber { get; set; }
public string SectionName { get; set; }
public int QuestionNumber { get; set; }
public string QuestionName { get; set; }
}
SectionItemList.cs (DTO)
public class SectionItemList
{
public int Id { get; set; }
public int SectionNumber { get; set; }
public string SectionName { get; set; }
}
QuestionnaireItemsController:
public class QuestionnaireItemsController : ApiController
{
private SQAContext db = new SQAContext();
// GET: api/QuestionnaireItems
[HttpGet]
public IQueryable<QuestionItemList> GetItems()
{
var items = from a in db.QuestionnaireItems
select new QuestionItemList()
{
Id = a.PID,
SectionNumber = a.QuestionnaireSection.Number,
SectionName = a.QuestionnaireSection.Name,
QuestionNumber = a.Number,
QuestionName = a.Name
};
return items;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool QuestionnaireItemExists(int id)
{
return db.QuestionnaireItems.Count(e => e.PID == id) > 0;
}
}
QuestionnaireSectionsController:
public class QuestionnaireSectionsController : ApiController
{
private SQAContext db = new SQAContext();
// GET: api/QuestionnaireSections
[HttpGet]
public IQueryable<SectionItemList> GetSectionItems()
{
var items = from a in db.QuestionnaireSections
select new SectionItemList()
{
Id = a.PID,
SectionNumber = a.Number,
SectionName = a.Name
};
return items;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool QuestionnaireSectionExists(int id)
{
return db.QuestionnaireSections.Count(e => e.PID == id) > 0;
}
}

Button Click is not calling an Action

When I click the Post button I want to add a message to my database but now it is not working. When I click the button nothing happens and the AddMessage Method in my Home Conroller never gets called. DO you happen to know why?
Chat View:
#{
ViewBag.Title = "Chat";
}
<h2 id="current-chat">General Chat</h2>
<div id="wrapper">
<div id="upper-wrapper">
<div id="available-rooms-dialog">
</div>
<div id="add-delete-room">
<input type="button" onclick="GetRoomName()" id="createroom" value="Create Room" />
<input type="button" onclick="DeleteRoom()" id="deleteroom" value="Delete Room" />
<form id="ava-rooms">
</form>
</div>
<div id="discussion-dialog">
<textarea rows="30" cols="50" id="discussion"></textarea>
</div>
</div>
<div id="message-dialog">
<textarea rows="3" id="message">Type your message</textarea>
<br/>
<input type="button" id="sendmessage" value="Post" />
<input type="hidden" id="displayname" />
</div>
</div>
#section scripts
{
<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<script type="text/javascript">
var json;
var currentRoomId;
setInterval(LoadRoomMessages(currentRoomId), 6000);
$(function () {
LoadRooms();
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
//===========================================================
//===================THIS LINE DIDNT DO SHIT=================
$.ajax(
{
type: "Get",
url: "#Url.Action("GetCurrentRoomId","Home")",
success: function (data) {
currentRoomId = data;
}
});
//==========================================================
//TODO: Add Record to Server
$.ajax(
{
type: "Post",
url: "#Url.Action("AddMessage", "Home")",
data: { messageCont: message.toString() },
success: function (data) {
LoadRoomMessages(currentRoomId);
}
});
};
//$('#sendmessage').click(AddMessage());
// Get the user name and store it to prepend to messages.
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
#*function AddMessage() {
$.ajax(
{
type: "Post",
url: "#Url.Action("AddMessage", "Home")",
data: { messageCont: message.toString() },
success: function (data) {
for (var i = 0; i < data.length; i++) {
//access with data[i].modelattribute
LoadRoomMessages(currentRoomId);
}
}
});
}*#
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function GetRoomName() {
var newRoomName = prompt('Enter a new Room Name', 'Name');
$.ajax(
{
type: "Post",
url: "#Url.Action("AddRoom", "Home")",
data: { chatRoom: newRoomName },
success: function (data) {
for (var i = 0; i < data.length; i++) {
//access with data[i].modelattribute
}
$('#ava-rooms').empty();
LoadRooms();
}
});
}
function DeleteRoom() {
var roomname = prompt('Enter a Room Name to be Deleted', 'Room Name');
$.ajax(
{
type: "Post",
url: "#Url.Action("DeleteRoom", "Home")",
data: { chatRoom: roomname },
success: function (data) {
for (var i = 0; i < data.length; i++) {
//access with data[i].modelattribute
}
$('#ava-rooms').empty();
LoadRooms();
}
});
}
function LoadRooms() {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetRooms", "Home")",
success: function (data) {
json = data;
var obj = JSON.parse(json);
GetUserPicture();
for (var i = 0; i < data.length; i++) {
//access with data[i].modelattribute
// Add an Onlick event to this statment that calls LoadRoomMessages
//onclick="GetRoomName()"
$('#ava-rooms').append("<input type=\"button\" " + "onclick=LoadRoomMessages(" + obj[i].Id + ") " + "id=\"" + obj[i].RoomName + "\"" + "value=\"" + obj[i].RoomName + "\" />");
}
}
});
}
function GetUserPicture() {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetUserPicture", "Home")",
success: function (data) {
$('.body-content').css("background-image", "url(\"" + data + "\")");
}
});
}
function LoadRoomMessages(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetMessages", "Home")",
data: { roomId: id },
success: function (data) {
$('#discussion').empty();
json = data;
var obj = JSON.parse(json);
for (var i = 0; i < data.length; i++) {
$('#discussion').append(htmlEncode(obj[i].Author) + " : " + htmlEncode(obj[i].Message) + "\r\n");
}
}
});
}
</script>
}
Home Controller:
using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using SignalRChat.Models;
namespace SignalRChat.Controllers
{
public class HomeController : Controller
{
ChatDBEntities DB = new ChatDBEntities();
ChatDBEntities1 DB_Uno = new ChatDBEntities1();
ChatDBEntities2 DB_Dos = new ChatDBEntities2();
public ActionResult Chat()
{
return View();
}
public ActionResult Users()
{
return View();
}
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpGet]
public string GetUserPicture()
{
try
{
var authorId = (int)Session["currentUserId"];
var pic = DB_Dos.ChatRoomUsers.Find(authorId).PictureURL;
if (String.IsNullOrWhiteSpace(pic))
return "http://www.adventuredogblog.com/wp-content/uploads/2014/03/3.jpg";
else
{
return pic;
}
}
catch (Exception)
{
return "http://www.adventuredogblog.com/wp-content/uploads/2014/03/3.jpg";
}
}
[HttpPost]
public bool AddMessage(string messageCont)
{
var authorId = (int) Session["currentUserId"];
var message = new ChatMessage();
message.Author = DB_Dos.ChatRoomUsers.Find(authorId).UserName; // Add Code to get the actual user
message.AuthorId = authorId; ; //Add Code to get current user Id
message.Message = messageCont;
message.MessageDate = DateTime.UtcNow;
message.RoomId = (int)Session["currentRoomId"]; ; //Add Room Code
message.RoomName = DB_Uno.ChatRooms.Find(message.RoomId).RoomName; // Get actual name based on id
try
{
DB.ChatMessages.Add(message);
DB.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
[HttpGet]
public int GetCurrentRoomId()
{
return (int) Session["currentRoomId"];
}
[HttpGet]
public string GetMessages(int roomId)
{
Session["currentRoomId"] = roomId;
var messages = (from message in DB.ChatMessages where message.RoomId == roomId orderby message.MessageDate ascending select message).ToList();
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(messages);
return json;
}
[HttpPost]
public bool AddRoom(string chatRoom)
{
var room = new ChatRoom();
room.IsActiveRoom = true;
room.RoomName = chatRoom;
room.isDefaultRoom = false;
room.UserCount = 1;
room.Id = -1;
try
{
DB_Uno.ChatRooms.Add(room);
DB_Uno.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
[HttpPost]
public bool DeleteRoom(string chatRoom)
{
var userId = (from u in DB_Uno.ChatRooms where u.RoomName == chatRoom select u.Id).ToList()[0];
var room = DB_Uno.ChatRooms.Find(userId);
var messages = (from u in DB.ChatMessages where u.RoomId == room.Id select u).ToList();
try
{
foreach (var message in messages)
{
DB.ChatMessages.Remove(message);
}
DB.SaveChanges();
DB_Uno.ChatRooms.Remove(room);
DB_Uno.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
[HttpGet]
public string GetRooms()
{
var rooms = DB_Uno.ChatRooms;
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(rooms);
return json;
}
public ActionResult AddUser()
{
return View();
}
[HttpPost]
public ActionResult AddUser(ChatRoomUser user)
{
var users = DB_Dos.ChatRoomUsers;
try
{
user.LastActivity = DateTime.UtcNow;
user.RoomId = 1;
user.RoomName = "General Chat";
users.Add(user);
DB_Dos.SaveChanges();
Session["currentUserId"] = user.UserId;
return View("Chat");
}
catch(Exception)
{
return View();
}
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(ChatRoomUser LUser)
{
var userId = (from u in DB_Dos.ChatRoomUsers where u.UserName == LUser.UserName select u.UserId).ToList();
var user = DB_Dos.ChatRoomUsers.Find(userId[0]);
if(user.password == LUser.password)
{
user.LastActivity = DateTime.UtcNow;
Session["currentRoomId"] = user.RoomId;
Session["currentUserId"] = user.UserId;
DB_Dos.SaveChanges();
return View("Chat");
}
else
{
return View();
}
}
}
}
You need to use form action attribute to point it to your controller or use i.e.Html.BeginForm and put your buttons inside the form

tryupdatemodel does not work through ajaxcall?

i am trying to post my model to the server through an ajax call. Unfortunately the Model is not updated?
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<form id="ajaxForm" action="">
<div>
name:<%= Html.TextBoxFor(model => model.number) %>
</div>
<%--hidden vars--%>
<input type="hidden" id="Hidden1" />
<%= Html.Hidden("myModel", Model.Serialize())%>
</form>
<button id="submitbutton">
save
</button>
<script type="text/javascript">
$(document).ready(function () {
$("#submitbutton").click(function () {
var FormData = $("#ajaxForm").serialize();
$.ajax({
type: 'POST',
url: "/Home/SaveAjax",
data: { inputdata: $("#myModel").val() },
datatype: 'JSON'
});
})
});
</script>
[HttpPost]
public JsonResult SaveAjax(string inputdata)
{
MyModel myModel = (inputdata.DeSerialize() ?? TempData["myModel"] ?? new MyModel()) as MyModel;
//TryUpdateModel does not update my model??
TryUpdateModel(myModel);
TempData["myModel"] = myModel;
return Json(new { resultaat = "finished" });
}
[Serializable]
public class MyModel
{
//[Required]
public string name { get; set; }
public bool flag { get; set; }
public int number { get; set; }
public string address { get; set; }
public string abn { get; set; }
public string postalcode { get; set; }
}
public static class Extensions
{
public static string Serialize(this object myobject)
{
var sw = new StringWriter();
var formatter = new LosFormatter();
formatter.Serialize(sw, myobject);
return sw.ToString();
}
public static object DeSerialize(this string mystring)
{
if (string.IsNullOrEmpty(mystring))
return null;
var formatter = new LosFormatter();
MyModel mym = (MyModel)formatter.Deserialize(mystring);
return mym;
}
}
In your AJAX request you are sending only the value of the hidden field:
data: { inputdata: $("#myModel").val() }
so you cannot expect to get any other values on your server than this hidden field. If you want to POST the entire form contents use the formData variable that you declared in your code but left unused:
$('#submitbutton').click(function () {
var formData = $('#ajaxForm').serialize();
$.ajax({
type: 'POST',
url: '/Home/SaveAjax',
data: formData,
dataType: 'json'
});
});

Categories