in my project I have a form with 2 dropdownlist and by clicking a button
it should search in DB and return list of results. this dropdownlist can also be null.
every time I click the button and sent values to my controller via ajax
it shows this error for all my values:
Object reference not set to an instance of an object.
this is my ajax code:
var ValCourse = $("#ddlCourseName").val();
var ValTeacher = $("#ddlTeachers").val();
var CurrentCourseModel = {
CourseNameID: ValCourse,
CourseTeacherID: ValTeacher,
}
var viewModel = {
"CurrentCourseModel": CurrentCourseModel
}
$.ajax({
type: "POST",
url: UrlFindCourse,
data: JSON.stringify(viewModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (response) {
alert("Success");
}
error: function (response) {
alert("Error");
}
});
and this is my ActionResut:
public ActionResult Courses(CourseModelView viewModel)
{
try
{
CourseRepository repository = new CourseRepository();
CourseModelView model = new CourseModelView();
model.CurrentCourseModel.CourseNameID = viewModel.CurrentCourseModel.CourseNameID;
model.CurrentCourseModel.CourseTeacherID = viewModel.CurrentCourseModel.CourseTeacherID;
model.CurrentCourseModels = repository.FindCourse(model.CurrentCourseModel);
return View(model);
}
catch (Exception Err)
{
LogRepository.Logs.WriteDebug(Err, "error");
return View("~/ HttpError / 500.html");
}
}
the ajax receives all the value correctly I tested that.
but action result says all my values are null
please help me
thank you
you better create a special viewmodel for ajax
public class ViewModel
{
public int CourseNameID {get; set;}
public int CourseTeacherID {get; set;}
}
try this ajax
$.ajax({
type: "POST",
url: UrlFindCourse,
data: { viewModel:viewModel},
success: function (response) {
alert("Success");
}
error: function (response) {
alert("Error");
}
});
and fix the action too
public ActionResult Courses(ViewModel viewModel)
{
CourseModelView model = new CourseModelView{ CurrentCourseModel=new CurrentCourseModel()};
model.CurrentCourseModel.CourseNameID = viewModel.CourseNameID;
model.CurrentCourseModel.CourseTeacherID = viewModel.CourseTeacherID;
model.CurrentCourseModels = repository.FindCourse(model.CurrentCourseModel);
PS. I had to guess to write this code. Pls post CourseModelView class.
Related
I want to pass value from view to controller by using ajax.
<button onclick="addCommentByAjax()" >Save</button>
My script:
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
data: {
choiceId: "1"
}
});
}
Controller:
[HttpPost]
public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId)
{
//
}
but choiceId always null
Change couple of things.
First assign an id or class to your button.Second remove inline onclick function and use ajax click function.Then specify the request type as Post.
$('#btnComment').click(function () {
var choiceId = $('#YourChoiceId').val();
$.ajax({
url: '/Survey/DoDetailSurvey',
data: { 'choiceId' : choiceId},
type: "post",
cache: false,
success: function (response) {
//do something with response
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error occured');
}
});
});
Then your controller should look like this
[HttpPost]
public ActionResult DoDetailSurvey(string choiceId)
{
//
}
I don't know how you are populating your viewmodel,so I purposely removed them and shown an working example.
In case you want to pass viewmodel you should construct your data object like this:
var data = {};
data.Property1 = some val;
data.Property2 = "some val";
$.post('/Survey/DoDetailSurvey', data);
Sample structure of SurveyViewModel I assume:
public class SurveyViewModel
{
public int Property1 { get; set; }
public string Property2 { get; set; }
}
Since there are two parameter in your controller, you need to identify them both form the client side. Further, you should specify the contentType.
You spread the payload like so:
function addCommentByAjax() {
var payload = {
model: {
// whatever properties you might have
},
choiceId: 1
};
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
contentType: 'application/json',
data: JSON.stringify(payLoad)
});
}
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1'
}
});
}
You can also pass like this
or for more parameters
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun'
}
});
}
I have a test js function that should post data to webapi by Post method
function test() {
var puffs = [];
var puffObject = {
id: "2735943",
priority: "1"
};
puffs.push(puffObject);
puffs.push(puffObject);
var dto =
{
po: puffs
};
$.ajax({
type: "POST",
url: "../api/PuffPriority/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(dto),
dataType: "json",
success: function (data, status) {
if (data) {
console.log("Welcome");
} else {
console.log("No data");
}
},
error: function (error) {
console.log("Error");
}
});
}
In the controller class i have
public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}
where PuffPriority Model is
public class PuffPriority
{
public string id { get; set; }
public string priority { get; set; }
}
I dont know whats wrong , the values are sent by JS but api Controller don't fetch it :( Please help, i have already wasted a lot of time.
You have a bug in your code.
Simply change
url: "../api/PuffPriority/"
to
url: "../api/Post/"
or change your method name from Post to PuffPriority
Changed
public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}
To
[FromBody]List<PuffPriority> po{
//Do something here with po, but po is always empty
}
I am trying to pass the data of the view model to one js method and from there I need to pass the VM to another controller method to show the data.
here is what I have did:
$(document).ready(function () {
var content = GetHomeContent('/Home/CastContent');
if (content) {
saveBDContent('/Message/Details/', content);
}
});
function GetHomeContent(url) {
var modelData;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
contentType: 'application/json',
success: function (data) {
if (data) {
modelData = data;
}
},
error: function (data) {
status = false;
}
})
return modelData;
};
function saveBDContent(url, data) {
var status = false;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
if (data == "200") {
status = true;
}
},
error: function (data) {
status = false;
}
})
return status;
};
The problem am facing is , the content I retrived from the method show the namespace of the ViewModel. When I pass that to the new controlled the Viewmodel content is coming null.
Do I need to add anything to get/Pass the proper content ?
The Dummy method skeleton
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM);
}
I have missed out the JsonRequestBehavior.AllowGet in my controller method, I have added and the results are coming perfectly.
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM,JsonRequestBehavior.AllowGet);
}
and also I have set the HTTP status as post in the jquery method
Do something like that in the Controller:
public JsonResult QuickSave(BookEntry bookEntry) {
YourViewModel model = new YourViewModel();
return Json(model);
}
EDIT >> The associated Javascript code is :
$.ajax({
type: "POST",
url: 'The URL',
data: 'The JSON data',
dataType: "json",
success: function (theViewModel) {
// Do some JS stuff with your model
},
error: function (xhr, status, error) {
// Do some error stuff
}
});
Suppose I have a Action which return a JsonResult. Like below code:
public ActionResult testAction()
{
return Json(new { name="mike",age="20"});
}
It json an anonymous object and return it. Then I want to write below code in View (.cshtml) file with razor engine.
#{
JsonResult m = ///some method can help me get the JsonResult
//Then I can print the value of m
#m.Data.ToString()
}
How to do it?
why do you use json result in view? You can:
public ActionResult testAction()
{
return View(new Model{ name="mike",age="20"});
}
In your View, you can call your testAction method via an Ajax call, then access to your returned object. But as far as I know, you must return a model.
Create a Model
public class YourModel
{
public string Name { get; set; }
public int Age { get; set; }
}
A Controller :
public ActionResult testAction(string name, int age)
{
YourModel ym = new YourModel();
ym.Name = name;
ym.Age = age;
return Json(ym, JsonRequestBehavior.AllowGet);
}
Your View :
var name = "Mike";
var age = "20";
$.ajax({
url : "#Url.Action("testAction", "YourController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({name: name, age: age})
}).done(function (data) {
alert(data); // Do what you want with your object, like data.Name
})
This is a dummy example because you pass parameter from the view to the controller, then send them back to the view, but I think this sample can help you to better understand how to play with Ajax call in ASP.NET MVC3. Ajax call is asynchronous, but thank to deferred .done, you wait for the end of the server call to ensure your data object is filled
You have to use ajax to read.
$.ajax({
url: "/YourController/testAction/",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: json,
type: 'POST',
success: function (data) {
setTimeout(function () {
//find your html element and show.
$("#ShowSomewhere").val(data.name);
}, 500);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
try use Html.Action("actionName");
this return a string
I have an ajax POST like this
$(document).ready(function () {
var pcontent = document.body.innerHTML;
var url = new URI();
$.ajax({
url: url,
type: "POST",
data: { "pcontent": pcontent },
success: function (data) {
alert($(data).find(".right-panel").html());
},
complete: function () {
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status) {
alert(jqXHR.responseText);
} else {
alert("Something went wrong");
}
}
});
return false;
});
I am little confused how i could retrieve data (pcontent) that i post here in my code behind.actually in a specific class file i need to implement this logic .
You have to create a controller action:
public class HomeController: {
// model
public class PDocument {
public string pcontent {get;set;}
}
[HttpPost]
public ActionResult SaveDocument(PDocument pcontent){
// do something
return new JsonResult() { Data = new { Success = true } };
}
}
JS:
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: { "pcontent": pcontent}
...});
Note:
You don't need to create a model on server if set
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: pcontent
});
// server side
public ActionResult SaveDocument(string pcontent){
// do some thing
}
For security reason, your html must be encoded before calling ajax
In case you new to mvc, then this is a good way to start: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller