public enum SocialEnum
{
[Display(Name = "Genel")]
General,
[Display(Name ="Teşekkür Et")]
Thanks
}
public class SocialMedia : Entity<string>
{
public string Message { get; set; }
public string Departmen { get; set; }
public SocialEnum MessageType { get; set; }
public string FullName { get; set; }
}
This is my model
<div class=" right floated" id="SubjectButtons">
<button class="tiny ui inverted blue button General" id="general"><i class="globe icon"></i>Genel</button>
<button class="tiny ui inverted blue button Thanks" id="thanks"><i class="star icon"></i>Teşekkür Et</button>
</div>
this is my cshtml
$(function () {
$('#Share').on('click', function () {
var file = $("#imgupload").get(0).files;
var droplist = $(".ui.fluid.search.dropdown").val();
var message = $(".ui.form").val();
var sbjtbtn = $("#general").val();
var sbjtbtn = $("#thanks").val();
var data = new FormData;
data.append("Photo", file[0]);
data.append("Message", message);
data.append("FullNameList", droplist);
data.append("MessageType", sbjtbtn);
$.ajax({
url: '#Url.Action("Index")',
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (data) {
$(".post-area").html(Counter);
$(".post-area").html(data);
$("#message").html(data.message);
$(".img-responsive").append('<img src="/Image/' + data + '"class=img-responsive thumbnail"/>');
if (sbjtbtn == $("#thanks")) {
$("#person").html(data.droplist);
$(".post-area").html(data);
$("#message").html(data.message);
$(".img-responsive").append('<img src="/Image/' + data + '"class=img-responsive thumbnail"/>');
}
},
error: function (data) {
}
});
});
});
this is my js
public ActionResult Index(SocialMedia data)
{
var model=GetSocialMedia();
MediaList mediaList = new MediaList();
if (mediaList.MessageType == data.MessageType)
{
mediaList.FullName = model.FullName;
mediaList.Departmen = model.Departmen;
mediaList.Message = data.Message;
var file = data.Photo;
if (file != null)
{
string Location = Server.MapPath("/Image/" + file.FileName);
file.SaveAs(Location);
mediaList.Photo = "../Image/" + file.FileName;
}
mediaList.FullNameList = data.FullNameList;
}
return PartialView("~/Views/SocialMedia/MediaList.cshtml", mediaList);
}
This is my controller
When you press the general button, some data should come. but if you press the thanks button, it should pull more data. I have defined it separately in ajax. I gave the variable name the same. message type comes in general.The message type is never be thanks.Where is my mistake?
My index page, model and controller are longer, but I think these are the parts I need to show.Sorry for my English:)
you should know already what is the difference between view and model. In any case in index view place this div
.....
<div id="mediaList">
<partial name="~/Views/SocialMedia/MediaList.cshtml" />
</div>
.....
<div class=" right floated" id="SubjectButtons">
<button class="tiny ui inverted blue button General" id="general"><i class="globe icon"></i>Genel</button>
<button class="tiny ui inverted blue button Thanks" id="thanks"><i class="star icon"></i>Teşekkür Et</button>
</div>
and ajax
$.ajax({
url: '#Url.Action("Index")',
.....
success: function (data) {
$("#mediaList").html(data);
},
error: function (xhr) {
}
});
have you tried using POSTMAN tool? https://www.postman.com/ . This tool is used for testing webservice API. Try this one first if you really get some data from your API URL.
Related
I have some kind of messenger it have panel by side where I can see all my contacts. What I want is when i click on one of them to pass phone number and Id to my Controller to send message and save it in database.
Foreach prints all my contacts:
#foreach (var contact in Model.Contacts)
{
<div class="chatperson" onclick="get_contact_number(#contact.PhoneNumber , #contact.ContactId)">
<div class="namechat">
<div class="pname">
#contact.Name
<a asp-action="ContactDetails" asp-route-id="#contact.ContactId" class=" glyphicon glyphicon-info-sign"></a>
<a asp-action="EditContact" asp-route-id="#contact.ContactId" class=" glyphicon glyphicon-pencil "></a>
</div>
<div class="lastmsg">#contact.PhoneNumber </div>
</div>
</div>
}
In div I used JS method and passed there values:
function get_contact_number(contactNumber, contactId) {
#Model.PhoneNr = contactNumber;
#Model.ContactId = contactId;
}
In final i want to pass these values to my controller function
public IActionResult SendMessage(MessengerViewModel model, string phoneNumber, string message)
{
var CurrentUserId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
if (ModelState.IsValid)
{
var newMessage = new Message();
newMessage.UserId = CurrentUserId;
newMessage.ContactId = model.ContactId;
newMessage.Body = model.MessageBody;
newMessage.Date = DateTime.Now;
newMessage.isDelivered = true;
_messageService.AddMessage(newMessage);
AtSmsSender smsSender = new AtSmsSender();
message = model.MessageBody;
phoneNumber = model.PhoneNr;
smsSender.SendSms(phoneNumber, message);
return RedirectToAction("Index", "Messenger");
}
else
{
return RedirectToAction("Index", "Messenger");
}
}
you can do a ajax call from get_contact_number function. Something like the below code
$.ajax({
type:'GET',
url: '#Url.Action("ActionName", "ControllerName")',
async:true,
success:function(response){
//Do Something With response object returned by your action
}
});
I'm trying to bind and display 4 concatenate item in dropdownlist using ajax.
Like this eg. (127,CoilWt,1,KGS ) one of the value in dropdownlist should appear like this.from database.
In database i am selecting
`select CODE_VALUE,CODE_DESC,CODE_SUB_VALUE,CODE_SUB_DESC FROM TCODE
html part
<td><select class='form-control' id='Certific'><option value='' disabled='disabled' selected='selected'>Please select a name</option></select></td>
script part
$(function () {
$.ajax({
type: "POST",
url: "TDC.aspx/GetCertificate",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var Certific = $("[id*=Certific]");
Certific.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
Certific.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
c# side
public class GetCertificate
{
public int ID { get; set; }
public string Code_Desc { get; set; }
}
[WebMethod]
public static List<GetCertificate> GetCertificate()
{
string connStr = ConfigurationManager.ConnectionStrings["conndbprodnew"].ToString();
OracleConnection objconn = new OracleConnection(connStr);
string prop_name, tdc_property = "", qry = "";
qry = "SELECT CODE_DESC from tdc_product1 ";
OracleCommand objFetchCmd = new OracleCommand(qry, objconn);
List<GetCertificate> Certificate = new List<GetCertificate>();
objconn.Open();
OracleDataReader ReadData = objFetchCmd.ExecuteReader();
while (ReadData.Read())
{
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
}
return Certificate;
}
Where is the mistake i am trying like this but getting error at GetCertificate.ID .Any idea would be appreciated.
I guess you're making mistake at:
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
GetCertificate seems to be a type not a instance of object.
You should try something like:
Certificate.Add(new GetCertificate { ID = ReadData["ID"].ToString(), CODE_DESC = ReadData["CODE_DESC"].ToString() } );
Please be aware that I wrote this without any IDE, so there could be typo/syntax error, but you get the idea.
Small hint: Of course there're plenty of room for code refactor in your code (e.g. rename Certificate to Certificates), but that is another topic.
I am working on a project in Visual studio using MVC. I am trying to reload a div after a btn is clicked and data has been posted to the controller dynamically. I use an Ajax post and return a JSONresult. The code for posting looks like this:
<div id = "DelUser">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Dform" }))
{
<label> Select User(s) to Delete: </label>
#Html.ListBox("Users", ViewBag.Users as MultiSelectList,
new { #class = "chzn-select", #style = "width:250px; height:350 px" })
}
<button class="btn btn-primary dropdown-toggle" id="Button1" type="button" onclick="DeleteUsers()"> Delete Selected </button>
</div>
<script>
function DeleteUsers() {
var myList = []
$("#Users > option:selected").each(function () {
myList.push($(this).val());
});
jQuery.ajax({
type: 'post',
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: 'DeleteU',
data: JSON.stringify(myList),
success: function (data) {
$('#msgbx2').html(data.msg);
//here I am trying to refresh the div after the post but it fires every second
$('#DelUser').html('/Home/DeleteUser');
},
failure: function (errMsg) {
$('#msgbx2').html(data.msg);
}
});
return false;
}
The name of the controller is DeleteUser and the JSONresult controller is DeleteU.
I am trying to do this so that the dropdownlist updates after I delete the selected users. If there is another way to dynamically update this div, any information on that would be good to know too. Thank you in advance.
Here are the Controllers as well:
[HttpGet]
public ActionResult DeleteUser()
{
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] user in users)
{
u.Add((string)user[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
return View();
}
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{
bool good = false;
if (Users != null)
{
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
good = data.insert_update_delete_DB(ins);
List<string> u = new List<string>();
object[] users = data.getDataFrmDB("Select username From `users`;");
if (users != null)
{
foreach (object[] usera in users)
{
u.Add((string)usera[0]);
}
}
ViewBag.Users = new MultiSelectList(u, "Username");
if (good == true)
{
ViewBag.error = "You have successfully deleted user";
}
else
{
ViewBag.error = "There was an issue removing user";
}
}
return Json(new { msg = "You have Successfully deleted Users " });
}
return Json(new { msg = "the passwords entered do not match" });
}
This is just a section of my main page that has other action functions/controllers in it which is why i did not originally post the controllers
You can simply update the existing listbox by removing the currently selected items. Start by removing onclick="DeleteUsers() from the button and use Unobtrusive JavaScript. Since you do not appear to have a POST method for DeleteUser() or a submit button, you may as well also replace #using (Html.BeginForm(...)) with just <form> elements. The script will then be
$('#Button1').click(function () {
var selected = $('#Users option:selected'); // store the selected users
if (selected.length == 0) {
return; // no point making a post
}
var users = [];
$.each(selected, function (index, item) {
users.push($(this).val());
})
$.ajax({
type: 'post',
dataType: 'json',
url: '#Url.Action("DeleteU", "yourControllerName")', // always use Url.Action to generate your url's
data: { users: users },
traditional: true,
success: function () {
// remove the currently selected options
selected.remove();
}
});
})
However a lot of the code in your controller does not make sense. Your adding values to ViewBag and even creating a SelectList but your not returning a view (your returning json), so all that is lost. And even if you were returning a view, your loop keeps overwriting the value of ViewBag.error so that only the last value would be set. Ideally, you should be calling a service to delete the users by passing the user name (or a collection of user names so that they are all deleted in a transaction). But based on you current code, you controller method can be
[HttpPost]
public JsonResult DeleteU(List<string> Users)
{
if (Users == null)
{
// throw an error that can be caught in the ajax error handler
}
List<string> deletedUsers = new List<string>();
foreach (string user in Users)
{
string ins = "DELETE FROM `xcal-server`.`users` WHERE username='"+user+"';";
if (data.insert_update_delete_DB(ins))
{
deletedUsers.Add(user);
}
}
return Json(deletedUsers);
}
and then the ajax success callback
success: function (data) {
$.each(data, function(index, item) {
// remove each item that was successfully deleted in the controller
$('#Users option:contains("' + item + '")').remove();
}
}
i think you need to add a $(document).ready(function(){}); around your script
I am trying to get the value of an item in a dropdownlist and pass it to the controller using an ajax post, but whatever I pass keeps returning as null.
DropDownList:
<div class="form-inline">
#Html.DropDownList("People", null, new { #id = "personID", #class = "form-control" })
<button onClick="setTimeout( initCalendar, 5000 );" type="button" id="btnInit" data-backdrop="static" data-keyboard="false" data-toggle="modal" href="#loadingModal" class="btn btn-info">Initialise Calendar</button>
</div>
ajax post:
function initCalendar() {
// This function will be executed when you click the element
// show the element you want to show
$("#loadingModal").show();
alert($('#personID').val(""));
//var dataRow = {
// 'ID': $('#personID').val()
//};
var dataRow = $('#personID').val();
console.log(dataRow);
console.log($('#personID').length);
$.ajax({
type: 'POST',
url: "/Event/SelectPerson",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(dataRow)
});
startCalendar();
// Set a timeout to hide the element again
setTimeout(function () {
$('#loadingModal').modal('hide');
}, 5000);
}
Controller:
public ActionResult Index()
{
ViewBag.Hours = GetHoursList();
ViewBag.People = GetPeopleList();
return View();
}
// Finds all people in the database and adds them to a list for a dropdownlist.
public List<SelectListItem> GetPeopleList()
{
List<SelectListItem> peopleList = new List<SelectListItem>();
var people = from s in db.People
select s;
foreach (Person person in people)
{
peopleList.Add(new SelectListItem
{
Text = person.Forename + " " + person.Surname,
Value = person.ID.ToString()
});
}
//var sortedPeopleList = (from person in peopleList
// orderby person.Text
// select person).ToList();
return peopleList;
}
public void SelectPerson(int ID)
{
Person person = db.People.Where(p => p.ID == ID).FirstOrDefault();
Session["Person"] = person;
}
When I log the JSON, the ID is always null and I cant figure out why.
Thanks in advance.
The following line
alert($('#personID').val(""));
is setting the value of the element with id="personID" to null. You need to change it to
alert($('#personID').val());
try this one.
var dataRow = $('#personID').val();
Why after clickin on the button it display's nothing. And it do not invoke BooksByPublisherId. What i missed? How to fix this?
Controller
public class FoodController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult BooksByPublisherId(int id)
{
IList<BookModel> modelList = new List<BookModel>();
modelList.Add(new BookModel { Author = "Jhon", Year = "1970" });
modelList.Add(new BookModel { Author = "Nick", Year = "1977" });
modelList.Add(new BookModel { Author = "Joseph", Year = "1978" });
return Json(modelList, JsonRequestBehavior.AllowGet);
}
}
Model
public class BookModel
{
public string Title { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public decimal Price { get; set; }
}
View
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-2.2.0.js"></script>
<h2>Index</h2>
<button data-bind="click: capitalizeLastName">Load list</button>
<div class="results">Wait for list</div>
<script>
function AppViewModel() {
this.capitalizeLastName = function () {
debugger;
$.ajax({
cache: false,
type: "GET",
url: "Food/BooksByPublisherId",
data: { "id": id },
success: function (data) {
var result = "";
$.each(data, function (id, book) {
result += '<b>Title : </b>' + book.Title + '<br />' +
'<b> Author :</b>' + book.Author + '<br />' +
'<b> Year :</b>' + book.Year + '<br />' +
'<b> Price :</b>' + book.Price + '<hr />';
});
$('.results').html(result);
},
error: function (response) {
debugger;
alert('eror');
}
});
}
}
ko.applyBindings(new AppViewModel());
</script>
The only problem i can see in your code is, you are using a variable called id to build the js object you sent as the data for the ajax call, but it is not declared and initialized any value to it. In that you will get a script error like
Uncaught ReferenceError: id is not defined
Because of this script error, your other js code won't work ! As you see, the error is self explanatory. Just declare a variable id and set some value to it.
var id = 911;
$.ajax({
type: "GET",
url: "Food/BooksByPublisherId",
data: { "id": id },
// Your existing code
});
Also i see you have hardcoded the path to your action method. A better approach is to use the Html helper methods like Url.Action method to build the correct relative path to the action method.
url: "#Url.Action("BooksByPublisherId","Food")",
This will work if your js code is inside a razor view. If your code is inside an external js file, you might use the solution explained in this post.