Below is my area
Controller
public JsonResult Get_JSon()
{
List<AdminModule> mod = new List<AdminModule>();
mod.Add(new AdminModule { MyName = "1" });
mod.Add(new AdminModule { MyName = "2" });
mod.Add(new AdminModule { MyName = "3" });
return Json(mod);
}
Model
public class AdminModule
{
[Required]
public String MyName { get; set; }
}
View
#model _1.Areas.Admin.Models.AdminModule
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}
<div id="formContainer_Json" style="display:none"
data-url="#Url.Action("Get_JSon", "Admin", new { area = "Admin" })">
</div>
<input id="BTN_Json" onclick="return GetJsonR()" type="button" value="Button" />
#section Scripts {
<script type="text/javascript"
src="#Url.Content("~/areas/admin/scripts/myscript.js")"></script>
}
Scripts
function GetJsonR() {
var $formContainer = $('#formContainer_Json');
var url = $formContainer.attr('data-url');
$.get(url, null, function (data) { return false; });
return false;
}
Confusion is - When submitting the button to get Json result
500 Internal Server Error
Also in the title it is showing below info...
<title>This request has been blocked because sensitive information could be
disclosed to third party web sites when this is used in a GET request. To
allow GET requests, set JsonRequestBehavior to AllowGet.</title>
Replace the below line...
return Json(mod);
with below...
return Json(mod, JsonRequestBehavior.AllowGet);
Related
Small help required
1) I have created an html Dropdown in MVC view like this
<select name="Associateddl" id="Associateddl"></select>
2)I am appending the options to the dropdownlist using Jquery Ajax like
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'customservice.asmx/getallmember',
dataType: 'JSON',
success: function (response) {
var getData = JSON.parse(response.d);
console.log(getData.length);
if (getData.length > 0) {
$("#msg").hide();
$.each(getData, function (i, item) {
var optiontext = "";
optiontext = "<option value='" + item.Aid + "'>" + item.AMail + "</option>";
$("#Associateddl").append(optiontext);
});
}
else {
$("#msg").append("<p style='color:red'><b>Currently there are no members ,Please Add !!</b></p>");
}
},
error: function (err) {
//alert(err);
}
});
3)Now i want to retrive the dropdown selected value to controller from View.
My Model:
public class Event
{
[DisplayName("Event Name")]
[Required(ErrorMessage ="Event Name is Mandatory...")]
public string Eventname { get; set; }
[DisplayName("Event Year")]
[Required(ErrorMessage ="Enter the Year...")]
public int Year { get; set; }
[DisplayName("Associate ID")]
[Required(ErrorMessage ="Associate ID is required...")]
public string Associateddl { get; set; }
}
My Controller:
[HttpPost]
public ActionResult Index(Event eve)
{
string ename = eve.Eventname;
int eyr = eve.Year;
string eassociate = eve.Associateddl; //Here i want to retrive the dropdownselected Value
return View();
}
Please help me to get the Html dropdown seleted value to Controller from View.
Here is an example on how you can see the value of the ddl in the controller. I will get you an ASP.NET Fiddle you can click on that will host the solution.
web service
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string getallmember()
{
var drop2 = new List<SelectListItem>();
SelectListItem sli1 = new SelectListItem { Text = "MoreOptions1", Value = "1" };
SelectListItem sli2 = new SelectListItem { Text = "MoreOptions2", Value = "2" };
drop2.Add(sli1);
drop2.Add(sli2);
//GET NewtonSoft
var json = JsonConvert.SerializeObject(drop2);
return json;
}
Controller
public class HomeController : Controller
{
[HttpPost]
public ActionResult Tut118(string Associateddl)
{
//put breakpoint here
return View();
}
public ActionResult Tut118()
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut118</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
$.ajax({
type: "Post",
url: "customservice.asmx/getallmember",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#Associateddl").empty();
var theData = JSON.parse(response.d);
$.each(theData, function (i, anObj) {
$("#Associateddl").append($('<option>').text(anObj.Text).attr('value', anObj.Value));
});
}
,
error: function (request, status, error) {
alert(error);
}
});
})
})
</script>
</head>
<body>
<div>
#using (Html.BeginForm())
{
<input type="button" id="theButton" value="click to get ddl" />
<select name="Associateddl" id="Associateddl"></select>
<input type="submit" value="click after selecting ddl" />
}
</div>
</body>
</html>
I want to get the ID from URL in ASP.NET MVC Controller and insert it into Project_ID, the bellow is my code, i tried but its now working for me.
http://localhost:20487/ProjectComponent/Index/1
My Controller
[HttpPost]
public JsonResult SaveComponent(OrderVM O, int id)
{
bool status = false;
if (ModelState.IsValid)
{
using (Entities db = new Entities())
{
ProjComponent ProjComponent = new ProjComponent { project_id = id, title = O.title, description = O.description };
foreach (var i in O.ProjComponentActivities)
{
ProjComponent.ProjComponentActivity.Add(i);
}
db.ProjComponents.Add(ProjComponent);
db.SaveChanges();
status = true;
}
}
}
You can always use a hidden field and update it by jquery/javscript and send it to back end in ajax helper.....
Make sure 1.name should be exactly name as ActionMethod param and 3.Jquery ,jQuery Validate and jQuery unobstrusive ajax is loaded correctly
My code .cshtml
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div>
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.OnBegin = "OnBeginRequest";
options.OnSuccess = "OnSuccessRequest";
options.OnComplete = "OnCompleteRequest";
options.OnFailure = "OnFailureRequest";
// options.Confirm = "Do you want to Add Country ?";
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
#using (Ajax.BeginForm("AjaxSend", "Stackoverflow", options))
{
<input type="hidden" name="project_id" id="project_id" value="project_id" />
<input type="submit" value="Click me" />
}
</div>
<div id="divResponse">
</div>
<script>
$(function() {
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length - 1];
console.log(lastsegment);
$('#project_id').val(lastsegment);
});
function OnBeginRequest() {
console.log('On Begin');
}
function OnCompleteRequest() {
console.log('On Completed');
}
function OnSuccessRequest() {
console.log('On Success');
}
function OnFailureRequest() {
console.log('On Failure');
}
</script>
and Controller
[HttpPost]
public JsonResult AjaxSend(String project_id)
{
//rest goes here
return Json(new { Success = true });
}
this link may help link
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable
I have a controller
public class AccountDetailsController : Controller
{
private readonly IAccountStatsRepository _accountStatsRepository;
public AccountDetailsController(IAccountStatsRepository accountStatsRepository)
{
_accountStatsRepository = accountStatsRepository;
}
public ActionResult Details(string accountEmail)
{
var stats = _accountStatsRepository.Get(accountEmail);
var accountDetailsViewModel = new AccountDetailsViewModel
{
Email = accountEmail,
Money = stats.TotalCredits
};
return View(accountDetailsViewModel);
}
[OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)] // every 3 sec
public ActionResult GetLatestLogging(string email)
{
//if (email == null || email != null)
//{
var list = new List<LogViewModel>();
return PartialView("LatestLoggingView", list);
//}
}
}
And a View
#using FutWebFrontend.ViewModels
#model AccountDetailsViewModel
#{
ViewBag.Title = "Details";
}
<h2>#Model.Email</h2>
<div>
<h4>Account details</h4>
Money #String.Format("{0:0,0}", Model.Money)
</div>
<div id="loggingstream">
#Html.Partial("LatestLoggingView", new List<LogViewModel>())
</div>
<hr />
<dl class="dl-horizontal"></dl>
<p>
#Html.ActionLink("Back to List", "index", "AccountControl")
</p>
<script type="text/javascript">
$(function() {
setInterval(function () { $('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});
</script>
But when I go to my page and put a breakpoint in GetLatestLogging then nothing happens
If I hit F12 in chrome I get "Uncaught ReferenceError: $ is not defined "Details:67
From what I can gather, this should hit my Get method every 3 seconds, but I must have made a simple error somewhere
Try this
$( document ).ready(function() {
setInterval(function () {$('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});
My simpel test Model:
public class MovieModel {
public string SelectedCategorieID { get; set; }
public List<CategorieModel> Categories { get; set; }
public MovieModel() {
this.SelectedCategorieID = "0";
this.Categories = new List<CategorieModel>() {new CategorieModel {ID = 1,
Name = "Drama"},
new CategorieModel {ID = 2,
Name = "Scifi"}};
}
}
public class CategorieModel {
public int ID { get; set; }
public string Name { get; set; }
}
My Home controller action Index:
public ActionResult Index() {
Models.MovieModel mm = new Models.MovieModel();
return View(mm);
}
My strongly typed View:
#model MvcDropDownList.Models.MovieModel
#{
ViewBag.Title = "Home Page";
}
<script type="text/javascript">
function categoryChosen(selectedCatID) {
// debugger;
var url = "Home/CategoryChosen?SelectedCategorieID=" + selectedCatID;
$.post(url, function (data) {
$("#minicart").html(data);
});
}
</script>
#using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get)) {
<fieldset>
Movie Type
#Html.DropDownListFor(m => m.SelectedCategorieID, new SelectList(Model.Categories, "ID", "Name", Model.SelectedCategorieID), "---Select categorie---")
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
<input type="button" value="Minicart test" onclick="categoryChosen('#Model.SelectedCategorieID');" />
<div id="minicart">
#Html.Partial("Information")
</div>
Please ignore the first input, because I'm using the second input with 'Minicart test' on it (the HTML.Beginform is there to learn something else later). The mini cart stuff is from another tutorial, I apologize. Don't let it distract you please.
When the button is clicked categoryChosen jQuery is called, which calls the action:
[AcceptVerbs("POST")]
public ActionResult CategoryChosen(string SelectedCategorieID) {
ViewBag.messageString = SelectedCategorieID;
return PartialView("Information");
}
The partial view Information looks like this:
#{
ViewBag.Title = "Information";
}
<h2>Information</h2>
<h2>You selected: #ViewBag.messageString</h2>
My question is why is Model.SelectCategorieID zero (Model.SelectCategorieID = 0) even after I changed the value in the dropdownlist? What am I doing wrong? Thank you very much in advance for answering. If you need any information or anything in unclear, please let me know.
My question is why is Model.SelectCategorieID zero
(Model.SelectCategorieID = 0) even after I changed the value in the
dropdownlist?
That's because you have hardcoded that value in your onclick handler:
onclick="categoryChosen('#Model.SelectedCategorieID');"
If you want to do that properly you should read the value from the dropdown list:
onclick="categoryChosen(this);"
and then modify your categoryChosen function:
<script type="text/javascript">
function categoryChosen(ddl) {
// debugger;
var url = 'Home/CategoryChosen';
$.post(url, { selectedCategorieID: $(ddl).val() }, function (data) {
$('#minicart').html(data);
});
}
</script>
Also I would recommend you using an URL helper to generate the url to invoke instead of hardcoding it in your javascript function. And last but not least, I would recommend you doing this unobtrusively, so that you could put this in a separate javascript file and stop mixing markup and script.
So here's how your code will look like after taking into consideration my remarks:
#model MvcDropDownList.Models.MovieModel
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get))
{
<fieldset>
Movie Type
#Html.DropDownListFor(
m => m.SelectedCategorieID,
new SelectList(Model.Categories, "ID", "Name"),
"---Select categorie---",
new {
id = "categoryDdl"
data_url = Url.Action("CategoryChoosen", "Home")
}
)
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
<input type="button" value="Minicart test" id="minicart-button" />
<div id="minicart">
#Html.Partial("Information")
</div>
and then in your separate javascript file unobtrusively subscribe to the click handler of your button and send the AJAX request:
$(function() {
$('#minicart-button').click(function() {
// debugger;
var $categoryDdl = $('#categoryDdl');
var selectedCategorieID = $categoryDdl.val();
var url = $categoryDdl.data('url');
$.post(url, { selectedCategorieID: selectedCategorieID }, function (data) {
$('#minicart').html(data);
});
});
});
Provide an id for your dropdownlist:
#Html.DropDownListFor(m => m.SelectedCategorieID, new SelectList(Model.Categories, "ID",
"Name", Model.SelectedCategorieID), new {id = "myDropDownList"})
And your javascript function as follows:
<script type="text/javascript">
function categoryChosen() {
var cat = $("#myDropDownList").val();
var url = "Home/CategoryChosen?SelectedCategorieID=" + cat;
$.post(url, function (data) {
$("#minicart").html(data);
});
}
</script>
Why your code did not work?
onclick="categoryChosen('#Model.SelectedCategorieID')
is generated as
onclick="categoryChosen('0')
because the value of SelectedCategorieID is 0 when it is generated.
i've been trying to login through AJAX but somehow its not working.
my controller action is
public string CheckLogin(Users checkuser)
{
if (db.CheckUserLoginDetails(checkuser.Email, checkuser.Password))
{
return "Login Successful:" + checkuser.Email;
}
else
{
return "Login UnSuccessful";
}
}
my View AJAX code is
$(':submit').click(function (e) {
var username = $('#username').val();
var password = $('#password').val();
var postdata =
{
'Email': username,
'Password': password
};
$.post({
url: 'http://localhost:7651/Home/CheckLogin',
data: postdata,
success: function (msg) {
$('#Result').html(msg);
}
});
});
i don't know whats wrong in the code ..but some how its not making a call to controller action at all...
yes i am runing on localhost
CheckLogin action is i Home Controller
Routes are defualt...
will try to have a look on net panel.. dont have any idea on that
USERs Model
[Key]
public virtual int UserID { get; set; }
[Required(ErrorMessage="Required")]
public virtual string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
public virtual string LastName { get; set; }
[Required(ErrorMessage = "Required")]
[DataType(DataType.EmailAddress)]
public virtual string Email { get; set; }
[Required(ErrorMessage = "Required")]
[DataType(DataType.Password)]
public virtual string Password { get; set; }
[DataType(DataType.Date)]
public virtual DateTime JoiningDate { get; set; }
i have tried the breakpoints but the calls are not going and breakpoints are never hitting...
Result DIV exits in DOM .. in index view/ in HTML.BeginForm()
dont know how to add error to $.AJAX
Thanks for all the checklist though.... please help
here is the view ...
#model Temp1.Models.Users
#{
ViewBag.Title = "Index";
}
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js") type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.5.1-vsdoc.js") type="text/javascript"></script>
<h2>Login</h2>
#using (Html.BeginForm("CheckLogin", "Home"))
{
#*<p>
<input type="text" id="username" value="" />
</p>
<p>
<input type="password" id="password" value="" />
</p>
*#
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
<p>
<input type="button" value="Login" id="btnLogin" />
</p>
<div id="Result">
</div>
}
<script type="text/javascript">
$('#btnLogin').click(function (e) {
var postdata =
{
"Email": "temp#temp.com",
"Password": "temp123"
};
$.ajax({
url: '#Url.Action("CheckLogin","Home")',
data: postdata,
success: function (msg) {
$('#Result').html(msg);
},
error: function (data) {
$('#Result').html(msg);
}
});
});
</script>
Your ajax submit url should be like this '/controler/action'. The best practice is to use Url.Action("actionName","ControlerName") if not you will have to change your jQuery when you deploy somewhere else.
$.post({
url: '#Url.Action("CheckLogin","Home")'
data: postdata,
success: function (msg) {
$('#Result').html(msg);
}
});
if doing this only not working, try changing your action like this,
public string CheckLogin( string Email, string Password){
}
and change your postData,
var postdata =
{
Email: username,
Password: password
};
Your post leaves me with more questions than answers. I would spend some time debugging ...
Is your website running on port 7651?
is CheckLogin in your Home controller?
Are your routes the default routes, or what's your mapping like?
if you use net panel in FireBug do you see a request go out? What's the result of call?
Whats the "Users" model look like (could be a binding error)?
Have you put a breakpoint in an OnException method in your controller ?
Does #Result exist in your DOM (try an alert in the successfunction)?
have you tried adding the "error" property to your ajax call and interrogating the issue?
Your controller action is returning a string not an ActionResult which in this case would be a ContentResult.
Try:
public ContentResult CheckLogin(Users checkuser)
{
if (db.CheckUserLoginDetails(checkuser.Email, checkuser.Password))
{
return Content("Login Successful:" + checkuser.Email);
}
else
{
return Content("Login UnSuccessful");
}
}