I can not see the view 2 - ajax

I want also call view1 and view2 methods.but it does not work.the Method "SubmitMyData" works properly and return the views for my ajax call .after run i expected the execution (for example )view2. In this example i must see view2
[System.Web.Mvc.Route("Home/SubmitMyData/")]
[System.Web.Http.HttpPost]
public ActionResult SubmitMyData([FromBody]MyParamModel mydata)
{
if (mydata.Prop1.Equals("1"))
{
view1();
return View("view1");
}
else
{
view2();
return View("view2");
}
}
here is the bodies of views methods
public ActionResult view1()
{
ViewBag.Title = "view1";
return View();
}
public ActionResult view2()
{
ViewBag.Title = "view2";
return View();
}
and here is my ajax call (if necessary to see)
$('#Buttonv').click(function () {
var myData = {Prop1: "10", Prop2: ""};
$.ajax({
type: 'POST',
data: myData,
url: '/Home/SubmitMyData',
})
.success(function (data) {
$('#lblmessage').html(data);
})
.error(function (xhr, ajaxoption, thrownError) {
$('#lblmessage').html("moshkelo" + xhr + "ajaxoption= " + ajaxoption + " throwerror=" + thrownError);
})
//return false;
});

Replace your code view2(); with return RedirectToAction("view2");
You need to redirect to a action than just executing it like a method.
So your code would have to like below
public ActionResult SubmitMyData([FromBody]MyParamModel mydata)
{
if (mydata.Prop1.Equals("1"))
{
return RedirectToAction("view1");
//return View("view1"); // not required
}
else
{
return RedirectToAction("view2");
// return View("view2"); // not required
}
}

Related

ajax calls the mvc controller

why this code does not work?.I receive "ok" but i can not see the view1 (view1 not loaded).I want to manage the views by prop1 .If the value of prop1="1" load view1
Hier is my controller
[System.Web.Mvc.Route("Home/SubmitMyData/")]
[System.Web.Http.HttpPost]
public ActionResult SubmitMyData([FromBody]MyParamModel mydata)
{
if (mydata.Prop1.Equals("1"))
return View("veiw1");
else
return View("view2");
}
public class MyParamModel // #4
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
and it is my ajax call
$('#Buttonv').click(function () {
var myData = {Prop1: "1", Prop2: ""}; // #1
$.ajax({
type: 'POST',
data: myData, // #2
url: '/Home/SubmitMyData',
})
.success(function (data) {
var output = "ok";
$('#lblmessage').html(output);
})
.error(function (xhr, ajaxoption, thrownError) {
$('#lblmessage').html("moshkelo" + xhr + "ajaxoption= " + ajaxoption + " throwerror=" + thrownError);
});
//return false;
});
If you are returning a View from your Controller, you'll need to ensure that you are actually using the HTML content within the success callback of your POST :
.success(function (data) {
// data will contain your content
$('#lblmessage').html(data);
})
You were previous using output, which didn't seem to be defined anywhere within your script.
Additionally, you may want to check the name of the view that you are returning as return View("veiw1"); seems like a typo that should be return View("View1");.
In your javascript, you are ignoring the HTML returned by the server. Try changing it to...
.success(function (data) {
$('#lblmessage').html(data);
})
Per the documentation, the first parameter to the success method is the data returned by the server.

how to send serialized form to webapi Method

im trying to send my from with ajax( $.post ) to a webApi . ajax request run succesfull but when i send data to method in web api form collection get null then my method return "false"
please help me
My WebApi Method
[System.Web.Http.HttpPost]
public string AddRecord([FromBody]FormCollection form)
{
try
{
PersonBLL personbll = new PersonBLL();
var person = new tbl_persons();
person.firstname = form["txt_namePartial"];
person.lastname = form["txt_lastnamePartial"];
person.age = byte.Parse(form["txt_agePartial"]);
var result = personbll.AddRecord(person);
return result;
}
catch (Exception)
{
return "false";
}
}
my Ajax function
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",JSON.stringify(url) , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}
I often use that :
var form = $("#body").find("form").serialize();
$.ajax({
type: 'POST'
url: "/api/Person/AddRecord",
data: form,
dataType: 'json',
success: function (data) {
// Do something
},
error: function (data) {
// Do something
}
});
Get a try because I never used the FormCollection object type but just a model class.
This should be:
url=$("#form").serialize();
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",url , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}

Pass ViewModel + Parameter to action using ajax call

How do I pass a view model and another parameter to my action method using jquery ajax?
with what I'm doing now, the action method is not being called. I think the cause is probably because the parameters are not being passed correctly in the data object of the jquery ajax call:
jQuery ajax:
$('#form-login').submit(function (event) {
event.preventDefault();
$.ajax({
url: "/Account/LogOn/",
data: $('#form-login').serialize(),
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.userAuthenticated) {
window.location.href = data.url;
} else {
formBlock.clearMessages();
displayError($('#errorcred').val());
}
},
error: function () {
formBlock.clearMessages();
displayError($('#errorserver').val());
}
});
});
Action method (which accepts the view model and another parameter):
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
// Validate the email and password
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = true, url = returnUrl, isRedirect = true });
}
else
{
return Redirect(returnUrl);
}
}
else
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = true, url = Url.Action("Index", "Home"), isRedirect = true });
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
}
else
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = false, url = Url.Action("LogOn", "Account") });
}
else
{
ModelState.AddModelError("", adm.ErrorUserNamePassword);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Remove the following from the $.ajax call:
contentType: 'application/json; charset=utf-8',
You have specified application/json encoding but the $('#form-login').serialize() function is sending application/x-www-form-urlencoded content.
As far as sending the returnUrl parameter is concerned, you could simply read it from the form action where it should be present (if you used the Html.BeginForm() helper):
$.ajax({
url: this.action,
...
});
Also you probably want to rename the event variable with something else as this is a reserved word in javascript:
$('#form-login').submit(function (e) {
e.preventDefault();
...
});
The only way I have found to do this is to just include the second parameter in your viewmodel and continue to serialize your form the way you are doing now.

Model Binding and posting form via ajax

I want to post a form via ajax call also model will be passed into the action method, but want to get Model errors via json. How can I do this?
You could write a custom action filter:
public class HandleJsonErrors : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var modelState = (filterContext.Controller as Controller).ModelState;
if (!modelState.IsValid)
{
// if the model is not valid prepare some JSON response
// including the modelstate errors and cancel the execution
// of the action.
// TODO: This JSON could be further flattened/simplified
var errors = modelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new
{
x.Key,
x.Value.Errors
});
filterContext.Result = new JsonResult
{
Data = new { isvalid = false, errors = errors }
};
}
}
}
and then put it into action.
Model:
public class MyViewModel
{
[StringLength(10, MinimumLength = 5)]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[HandleJsonErrors]
public ActionResult Index(MyViewModel model)
{
// if you get this far the model was valid => process it
// and return some result
return Json(new { isvalid = true, success = "ok" });
}
}
and finally the request:
$.ajax({
url: '#Url.Action("Index")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
foo: 'abc'
}),
success: function (result) {
if (!result.isvalid) {
alert(result.errors[0].Errors[0].ErrorMessage);
} else {
alert(result.success);
}
}
});
Something like this?
$.ajax({
type: "POST",
url: $('#dialogform form').attr("action"),
data: $('#dialogform form').serialize(),
success: function (data) {
if(data.Success){
log.info("Successfully saved");
window.close();
}
else {
log.error("Save failed");
alert(data.ErrorMessage);
},
error: function(data){
alert("Error");
}
});
[HttpPost]
public JsonResult SaveServiceReport(Model model)
{
try
{
//
}
catch(Exception ex)
{
return Json(new AdminResponse { Success = false, ErrorMessage = "Failed" }, JsonRequestBehavior.AllowGet);
}

MVC Return Partial View as JSON

Is there a way to return an HTML string from rendering a partial as part of a JSON response from MVC?
public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
if (ModelState.IsValid)
{
if(Request.IsAjaxRequest()
return PartialView("NotEvil", model);
return View(model)
}
if(Request.IsAjaxRequest())
{
return Json(new { error=true, message = PartialView("Evil",model)});
}
return View(model);
}
You can extract the html string from the PartialViewResult object, similar to the answer to this thread:
Render a view as a string
PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.
Using the code from the thread above, you would be able to use:
public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
if (ModelState.IsValid)
{
if(Request.IsAjaxRequest())
return PartialView("NotEvil", model);
return View(model)
}
if(Request.IsAjaxRequest())
{
return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
}
return View(model);
}
Instead of RenderViewToString I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
$(function () {
$("select#ExamID").change(function (evt) {
var classid = $('#ClassId').val();
var StudentId = $('#StudentId').val();
$.ajax({
url: "/StudentMarks/ShowStudentSubjects",
type: 'POST',
data: { classId: classid, StudentId: StudentId, ExamID: $(this).val() },
success: function (result) {
$('#ShowStudentSubjects').html(result);
},
error: function (xhr) { alert("Something seems Wrong"); }
});
});
});

Resources