cshtml view not rendering - c#

I am using ASP.net MVC with the razor engine.
I have a page with a button, when the button is clicked i call an ActionResult in my controller using Ajax. The Ajax call:
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
//alert("yay");
}
});
My ActionResult method is hit fine, however it does not load the view speified.
The code:
public ActionResult Review()
{
return View();
}
The current view is Index.cshtml when Review() is hit i would like Review.cshtml to be rendered on screen. (It should be rendered as a full view, not as partial view inside Index.cshtml)
I have tried - return View("Review"); return View("Review.cshtml"); return View("..\Views\Home\Review.cshtml);
I can't use - tml.BeginForm("Action", "Controller", FormMethod.Post); (see my other question MVC submit button not firing)

Write the response directly to the screen
success: function (data) {
document.write(data) }

After ajax, you should render a partial view to add returning result to main view(index).
Index.cshtml
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
$("#container").html(data);
//alert("yay");
}
...
<div id="container"></div>
Controller
public ActionResult Review()
{
return PartialView();
}
If you want to redirect after ajax you can use something like following:
Index.cshtml
$.ajax({
type: "GET",
url: "/Home/Review",
success: function (data) {
window.location.href = data.url;
}
...
Controller
public ActionResult Review()
{
return Json(new { url = "some url" }, JsonRequestBehavior.AllowGet);
}

Related

.Net Core Binding

I am using .Net Core 2.1. This is the function that takes the value of the input boxName from the user and is supposed to pass it to the controller - Create function when the "save button" is clicked.
<script type="text/javascript">
function Submit() {
var boxName = $("#boxID").val();
alert(boxName);
UNTIL HERE EVERYTHING IS FINE - THE ALERT RETURNS THE CORRECT VALUE
$.ajax({
type: "POST",
contentType: "application/json",
url: '/Box/Create',
datatype: 'json',
data: JSON.stringify({ ID: "#Model.Id", BoxName: boxName }),
success: function (response) {
alert("Box created");
}
error: function (response) {
alert("error");
}
});
}
IN THE CONTROLLER
public ActionResult Create(int ID, string BoxName)
{
Box _Box = new Box();
_Box.Name= BoxName;
_db.Boxes.Add(_Box);
_db.SaveChanges();
return RedirectToAction("Index");
}
THE STRING BoxName RECEIVED AS A PARAMETER FROM THE AJAX IS NULL
I even tried
public ActionResult Create([Bind(Include = "ID,BoxName")] Box Box)
but it didn't work either. The error was
Include is not a valid named attribute argument
Any help is appreciated.
Remove the content Type and don't use stringify. So your ajax call becomes
$.ajax({
type: "POST",
url: '/Box/Create',
datatype: 'json',
data: { ID: "#Model.Id", BoxName: boxName },
success: function (response) {
alert("Box created");
}
Edit: This is partially wrong though you should do it for clarity. If there is only one action and the verb is not specified in your controller, the action is done anyway regardless if it's POST or GET.
You are using a POST verb in your ajax, by default all actions in the controller are GET. Add the [HttpPost] attribute above your controller action.
[HttpPost]
public ActionResult Create(int ID, string BoxName)
{
...
}
You should create a binding from the body of the request : ie:
class CreateBinding {
public string ID { get; set;}
public string BoxName { get; set; }
}
And in you controller:
[HttpPost]
Public ActionResult Create([FromBody] CreateBinding binding)
{
var id = binding.ID;
var name = binding.BoxName;
....
}

MVC: When returning from the controller on Ajax call, the result is undefined

I'm making an Ajax call to the controller when clicking on a Kendo button and return the model:
#(Html.Kendo().Button()
.Name("btnSubmit")
.HtmlAttributes(new { type = "button" })
.Icon("rotate")
.Content("View Details"))
<script>
$("#btnSubmit").click(function () {
$.ajax({
url: "/MyController/MyMethod/",
type: 'post',
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (result) {
window.location.href = "#Url.Action("RedirectToView", "MyController", new { myModel = "data" })".replace("data", result);
}
})
});
</script>
The controller's method returns the model:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyMethod()
{
var reportDate = Session["FileDate"] == null ? DateTime.Now : Convert.ToDateTime(Session["FileDate"].ToString());
var myModel = new MyModel();
myModel.ColOfData = myModel.GetColOfData(reportDate);
return Json(myModel, JsonRequestBehavior.AllowGet);
}
When I debug my Ajax function, result is undefined. The result should be assigned to MyModel, since I'm returning the model back to an Ajax function. I need to pass that result to another method in the controller that would return my Partial View containing the Grid:
public ActionResult RedirectToView(MyModel myModel)
{
return PartialView("_MyPartialView", myModel);
}
What am I doing wrong?
Your problem isn't related to kendo.
From your controller you have to return a json object like this
return Json(new {result=myModel});
And in your ajax result you will have your entire model.
After that from the code you provided I am afraid you can't pass your entire model in the url of your GET.
You could probably pass the model Id like that
window.location.href = "#Url.Action("RedirectToView", "MyController", new { id= "modelId" })".replace("modelId", result.Id);
And make your action something like that
public ActionResult RedirectToView(string id){
// Get the model data you want .....
return PartialView("_MyPartialView", myModel);
}

Return view with ViewModel after ajax call

i call an action from ajax function, get my ViewModel in it and then try to open new view with other ViewModel but redirectToAction and return view aren't working. Other answers i saw only got to opening other view without sending ViewModel with it
ajax call
$("#delete").click(function () {
var model = $("#forma").serialize();
console.log("delete", model);
$.ajax({
url: '#Url.Action("DeleteDevices", "package")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: model,
success: function (result) {
}
});
return false;
});
and contorller which does nothing
public ActionResult DeleteDevices(PackageDevicesViewModel viewModel)
{
//model processing here
return View(NewModel);
}
change
data: model,
to
data: JSON.parse(JSON.stringify($("form").serializeArray()))

ViewModel - repopulate form with new content after ajax requests

When I call an AJAX Get/Post, I can send a ViewModel of my form to my Controller methods. Is there a way to repopulate the form after this request with the new values of the ViewModel? What the right return of my method: a Json with the ViewModel or a View? Like this:
$.ajax({
dataType: "JSON",
data: $('#form').serialize(),
type: "GET",
url: "SomeController/doSomething",
success: function(myViewModel) {
// How to repopulate my form with the new values?
}
});
public class SomeController {
[HttpGet]
public ActionResult DoSomething(MyViewModel model) {
model.SomeProperty = "This property needs to be changed into the View.";
// The right way is returning a Json with the ViewModel...
return Json(model, JsonRequestBehavior.AllowGet);
// or return some View?
return View(model);
}
}
What will be returned is HTML. Can I suggest that you return a PartailView(model), this way it can be used throughout the system, you do not need to json encode it just use return PartialView(model). Put the Partial View in your Shared Folder.
public ActionResult DoSomething(MyViewModel model) {
model.SomeProperty = "This property needs to be changed into the View.";
return PartialView("MyPartialView", model);
}
Change the ajax to stringify the form, this will allow the model binding to work:
$.ajax({
dataType: "JSON",
data: JSON.stringify({model : $('#form').serialize() }),
type: "GET",
url: "SomeController/doSomething",
success: function(myViewModel) {
$('#myUlDropDownListID').replaceWith(myViewModel);
}
});
In your ajax you need to replace the HTML with the return, in this case you have called in myViewModel. I.e. if it is a table then you would do
$('#myUlDropDownListID').replaceWith(myViewModel);
This will replace the table with the new HTML

Action is unreachable after submitting a form

I have the following problem (I spend many hours looking for a solution).
The ‘Create’ button has a click event which calls the ‘Test’ action on the ‘Home’ controller.
All works fine.
When I hit the ‘Save’ button, to submit the form, that works fine to.
But after I have submitted the form, my ‘Create’ button stops working. The ‘Create’ button does have the click event, but the ‘Test’ action is unreachable?
index.cshtml
<script type="text/javascript">
$(document).ready(function () {
$("#create").click(function () {
$.ajax({
type: "POST",
traditional: true,
url: 'Home/Test',
dataType: "html",
success: function (data) {
alert('Succes!')
},
error: function () {
alert('A problem ocurred!!');
}
});
});
});
</script>
<input id="create" type="button" value="Create" />
#using (Html.BeginForm("SaveForm", "Home"))
{
<input type="submit" value="Save" />
}
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult Test()
{
return Content("Test result");
}
public ActionResult SaveForm()
{
return View("Index");
}
public ActionResult About()
{
return View();
}
}
All of your actions are GET only. Either add [HttpPost] (POST only) or [AcceptVerbs(HttpVerbs.Post, HttpVerbs.Get)] (GET or POST) attributes to your POST actions.
[HttpPost]
public ActionResult Test()
{
return Content("Test result");
}
[HttpPost]
public ActionResult SaveForm()
{
return View("Index");
}
Theres 2 problems:
1) you dont have [HttpPost] above your methods
2) You are not sending any data to your controller
add an id to your form by using an anonymous class:
#using (Html.BeginForm("SaveForm", "Home", new {id = "testform"}))
then rewrite the ajax request:
<script type="text/javascript">
$(document).ready(function () {
$("#create").click(function () {
$.ajax({
type: "POST",
data: $("#testform").serialize();
url: 'Home/Test',
dataType: "html",
success: function (data) {
alert('Succes!')
},
error: function () {
alert('A problem ocurred!!');
}
});
});
});
</script>
Let me know if it works :)
To create an entity, you have to submit your data to server, either by post back or ajax as in your case. Now there are some contradictions in your code :)
1. Why are you calling one action as form action and another through
ajax? Because since your button will post back, your ajax call won't
fire the success and error handlers. To solve this either use <button> or
$("#create").click(function (e) { e.preventDefault();//Some code});
2. If you want to use ajax, write it like this. Also write [HttpPost] on
your action. This indicates that this action can be called by post requests.
This is a required step, whether or not you are using ajax.
I hope this solved your problem.
Eventually I used Ajax.BeginForm instead of Html.BeginForm, added the [HttpPost] attributes to my actions and I used the RedirectToAction("Index") instead of PartialView. That solved my problem. Thanks again for your tips!

Categories