MVC: Edit Action is not invoking the Edit view - javascript

I have an Edit action. When the Action is invoked I expected the Edit view to render but it does not. The view is Edit.cshtml. I have a similar view Add.cshtml which works fine (Add is a button and Edit is a link inside the grid.
The Controller method
[HttpPost]
public IActionResult Edit(int Id)
{
try
{
var jurisdictionId = _user.Current().JurisdictionId;
OrganizationType ot = new OrganizationType();
ot.Id = Id;
ot.OrganizationName = _electedOfficials.getOrgTypeName(jurisdictionId, Id);
return View(ot);
//return View("Edit", ot);
}
catch (Exception e)
{
_logger?.LogCritical(new EventId(101, "CAdminOrganizationType"), e, $"Error when loading Edit Orginization Type View");
throw;
}
}
The Edit View (Edit.cshtml)
#model Platinum.Entities.OrganizationType
#{
ViewData["Title"] = "Editing Organization Type";
}
<div class="card pd-20 pd-sm-40">
<div class="form-layout">
<form asp-action="Edit">
<div class="row mg-b-25">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="Id" hidden />
<div class="col-md-2">
<div class="form-group">
<label asp-for="OrganizationName" class="form-control-label">Name</label>
<input asp-for="OrganizationName" class="form-control" />
<span asp-validation-for="OrganizationName" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-layout-footer">
<input type="submit" value="Create Organization Type" class="btn btn-default mg-r- 5" />
<a asp-action="Index" class="btn btn-danger mg-r-5">Back</a>
</div>
</form>
</div>
</div>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
});
</script>
}
The Javascript that executes when Edit is clicked in the Index view
function Edit(id) {
var url = '/CAdminOrganizationType/Edit/' + id
$.ajax({
type: "POST",
url: url,
contentType: "application/json"
}).fail(function () {
magalert.communicationError();
});
}

As far as I know, we couldn't render page without returning to ajax response.
Since the ajax will send the request to the controller action and the action returns the view as html response back to the ajax.
But you do not handle the response in ajax so that the current page will not change.
If you just want to pass the Id to Edit method and return the Edit view, I suggest you could try to use window.location, this will make this page redirect to the Edit view which achieve refresh the whole page.
Besides window.location only supports get method.I suggest you use [HttpGet] method to render the page, and then load the page in the success function in ajax.
Here is my code:
Ajax
#section Scripts
{
<script>
function Edit(id) {
var url = '/Home/Edit/' + id
$.ajax({
type: "get",
url: url,
contentType: "application/json",
success:function(){
window.location.href="/Home/Edit/"+id
},
error:function () {
magalert.communicationError();
}
});
}
</script>
}
The Controller Method
[HttpGet]
public IActionResult Edit(int Id)
{
try
{
var jurisdictionId = _user.Current().JurisdictionId;
OrganizationType ot = new OrganizationType();
ot.Id = Id;
ot.OrganizationName = _electedOfficials.getOrgTypeName(jurisdictionId, Id);
return View(ot);
}
catch (Exception e)
{
_logger?.LogCritical(new EventId(101, "CAdminOrganizationType"), e, $"Error when loading Edit Orginization Type View");
throw;
}
}
Then,you can load the View

Related

Returning json results at the same page in laravel

I have trouble returning my search results as json in same page that I searched,
this is my function for search page
public function track(Request $request){
return view('front.track');
}
this is route for it:
Route::get('/track', 'frontend\FrontendController#track')->name('track');
and this function to get results of my search
public function shippingcode(Request $request){
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxxxxxxxxxxxxxxxx');
$shippingcode = $request->input('shippingcode');
$item = Order::where('shippingcode', $shippingcode)->first();
$courier = $item->courier;
$results = $rajaongkir->waybill($shippingcode, $courier);
return response()->json($results);
}
and this is route for it:
Route::post('/shippingcode', 'frontend\FrontendController#shippingcode')->name('shippingcode');
and finally this is my search form in blade:
<form class="form-inline text-center" action="{{route('shippingcode')}}" method="post">
{{csrf_field()}}
<lable>Shipping Code #</lable>
<input type="text" class="form-control" name="shippingcode" placeholder="93657275025">
<button class="btn btn-success" id="submit" type="submit" name="button">Track</button>
</form>
Issue
Issue is except getting results bottom of my form I will redirect to another page and see results as JSON.
any idea?
UPDATE
I have added jquery to my page in order to get results but still i will redirect to another page:
JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('button[id="submit"]').on('click', function() {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
$.ajax({
url: '{{ url('shippingcode') }}',
type: "GET",
dataType: "json",
success:function(data) {
$('div#results').empty();
$("div#results").html(data);
}
});
});
});
</script>
and added this div bottom of my form <div class="col-md-8 col-md-offset-2" id="results"></div>
You need to prevent the default action of your form which is submitting the form via POST method to provided action URL.
Try adding -
$('button[id="submit"]').on('click', function(e) {
e.preventDefault();
// Your own login
});
SOLVED
Note: using e.preventDefault(); alone would not help at all, however
is necessary to have it.
Here is how I done it:
first of all I changed my function to code below:
public function shippingcode($code){
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxx');
$shippingcode = $code;
$item = Order::where('shippingcode', $shippingcode)->first();
$courier = $item->courier;
$results = $rajaongkir->waybill($shippingcode, $courier);
return response()->json($results);
}
and then I changed my route from POST to GET and added my {code} into it (look in my function).
Route::get('/shippingcode/{code}', 'frontend\FrontendController#shippingcode');
Finally I changed my JavaScript code to the following code. here I used e.preventDefault(); but pay attention how I got my button.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').on('click', function(e) {
e.preventDefault();
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var shippingcodedd = $("#code").val();
if(shippingcodedd) {
$.ajax({
url: '{{ url('shippingcode') }}/'+encodeURI(shippingcodedd),
type: "GET",
dataType: "json",
success:function(data) {
$('div#results').empty();
var summar = data.data.summary;
$('div#results').append('Data prints here!');
}
});
}else{
$('div#results').empty();
$('div#results').append('Sorry there is no info regarding to your tracking code in our system!');
}
});
});
</script>
PS: just for completeness here is my form HTML code:
<form class="form-inline text-center" action="" method="post">
{{csrf_field()}}
<lable for="shippingcode">Shipping Code #</lable>
<input type="text" id="code" class="form-control" name="shippingcode" placeholder="93657275025">
<button class="btn btn-success" id="submit" name="button">Track</button>
</form>
Hope it help others.

How do i submit form via ajax?

i'm trying to submit forms without post back via ajax ..my code doesn't work
whats wrong in my script?
i'm new to ajax..help me with ajax scripts..
below is my code
note: i have two submit buttons with in single view. I want to make ajax call for both submit actions
my view
#model AjaxEF.Models.Customer
#using (Html.BeginForm("Index", "Main", FormMethod.Post,new { id="idForm"}))
{
#Html.EditorForModel()
<br />
<input type="submit" name="save" value="Save" />
<input type="submit" name="cancel" value="Cancel" />
}
<script>
$("#idForm").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var url = "~/Main/Result"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function (data) {
alert(data); // show response from the php script.
}
});
});
</script>
my controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Customer obj, string save, string cancel)
{
if (!string.IsNullOrEmpty(save))
{
ViewBag.Message = "Customer saved successfully!";
}
if (!string.IsNullOrEmpty(cancel))
{
ViewBag.Message = "The operation was cancelled!";
}
return View("Result", obj);
}
public ActionResult Result()
{
return View();
}
Not sure why the other answer was deleted, but it was 100% correct. The URL you're hitting with your AJAX is your Result action, which does nothing but return a view. You need to post to your Index action, and since the form is already set to post there, the best way to get that URL for your AJAX is to select it from the form:
var url = $('#idForm").attr("action");

Using Jquery ajax to call ActionResult method in Controller and return data

I'm trying to understand how the Jquery Ajax methods works. Right now, I have some problems calling the ActionResult method in the controller that will return a PartialView.
Have created an button which I will use to get new data in from the server (Ajax call should run)
Code: (ActionResult in Home controller)
public ActionResult All()
{
List<Student> model = db.Students.ToList();
return PartialView("_Student", model);
}
This method is the one I'm trying to call when I press the button in the main Index view.
Code: (Index view)
<div class="row">
<div class="small-12 column sbw-travel">
<h2>Travel</h2>
<div class="row">
<div class="small-12 columns">
<button id="button1" class="sbw-travel-button">Search</button>
</div>
</div>
<div class="small-12 sbw-travel-box" id="rooms">
</div>
</div>
</div>
When the user hit the button, an Ajax call should run, and the list will appear in the section with id=rooms.
Script: (Ajax code)
$(document).ready(function () {
$('#button1').click(function () {
$.ajax({
type: 'GET',
url: #Url.Action("All", "Home"),
datatype: "html",
success: function () {
$('#rooms').html(???);
}
});
return false;
});
});
Can any of you see if I have forgot something to make this run like I have described?
The result is on the succes event. Try:
$(document).ready(function () {
$('#button1').click(function () {
$.ajax({
type: 'GET',
url: #Url.Action("All", "Home"),
datatype: "html",
success: function (data) {
$('#rooms').html(data);
}
});
return false;
}); });
I would suggest loading firebug when you click the button (enable the console), make sure the requested URI is responding with valid HTML data on the click event.
I also generally find using something like:
$('#button1').on('click', function () { ...
usually yields better results, see here: Difference between .on('click') vs .click()

how can i modify a freemarker variable value inside a success block in jQuery AJAX

how can i change a value of a freemarker variable inside a success block in jQuery AJAX, i have two controllers for my page the first one returns me a simple string with the name of the view with a GET method, the second one is the one that process the data using a json with a POST method
here they are
#RequestMapping(value = "myform", method = RequestMethod.GET)
public String formmethod(Model model) {
model.addAttribute("successMessage", "i'm in the firts controller");
return "forms/myform";
}
my second controller
#RequestMapping(value = "myform", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User userMapped= mapper.readValue(json, User.class);
User person = new Usuario();
person.setName("new name");
person.setLastName("new lastname");
model.addAttribute("successMessage", person.getName());
return toJson(userMapped);
}
my to Json method
private String toJson(User person)
{
ObjectMapper mapper = new ObjectMapper();
try
{
String value = mapper.writeValueAsString(person);
// return "["+value+"]";
return value;
}
catch (JsonProcessingException e)
{
e.printStackTrace();
return null;
}
}
and my page myform.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
function doAjaxPost()
{
// get the form values
var name= $('#name').val();
var lastName = $('#lastName ').val();
var json = {"name" : name, "lastName " : lastName };
console.log(json);
var FreeMarkervariable = "${successMessage}";
//this brings me the value that i put in the firts controller
$.ajax(
{
type: "POST",
url: "myform",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
//HERE I WANT TO CHANGE THE VALUE OF MY FREEMARKER VARIABLE SO I CAN
//PRINT A SUCCESS MESSAGE IN A DIV
<#assign successMessage = "success">
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
</script>
<!-- NEW WIDGET START -->
<article class="col-sm-12">
<div class="alert alert-warning fade in">
<button class="close" data-dismiss="alert">
×
</button>
<i class="fa-fw fa fa-warning"></i>
<strong>${successMessage} I WANT TO PRINT A SUCCESS MESSAGE HERE </strong>
</div>
</article>
<!-- WIDGET END -->
<fieldset>
<legend>Name in view</legend>
<form name="myform">
Name in view: <input type="text" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
</fieldset>
<br>
so far my freemarker variable gets the value that i put inside the success block but it appears "success" before i press my submit button, i believed that the succes block was executed after i hit the submit button so i dont know why it have the value even before i press the button it should have "i'm in the firts controller" before i press the submit button
Freemarker generates it's output on the server and this is then sent to the browser. The browser never sees any of the freemarker 'code'. You need to update the strong element using javascript/jQuery.
So instead of your <#assign...> use something like this
$("strong").text("Success");

Pass the result of AJAX callback to Partial View using JQuery

I'm using ASP.NET MVC 4. On a button click, I want to invoke ajax callback to controller method and return the data needed as Json Data. I'm able to do this using the following code:
<script>
$(document).ready(function () {
var ajax_url = '#Url.Action("GetNewItems")';
$("#submit").click(function () {
$.ajax({
url: ajax_url,
type: "POST",
datatype: "json",
success: function (data) {
debugger
}
});
});
});
[HttpPost]
public JsonResult GetNewItems()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Id = 3, Name = "c" });
items.Add(new Item() { Id = 4, Name = "d" });
return Json(items);
}
In success function, the collection of Items are returned properly. In this function, I want to call Html.Partial and pass the result as the model of the Partial view. Is this possible?
I've searched in other threads, but most of them are suggesting that Partial View is returned from Controller method and html(data) is used to render it. I'd rather not return the Partial view from Controller, as the size would have significant difference rather than returning the data only and render it manually in client-side.
So, is it possible to pass the result to Partial view in success function, or I have to manually render the elements in there?
Any help is appreciated. Thanks!
so what's the problem? just do it
[HttpPost]
public ActionResult GetNewItems()
{
List<Item> items = new List<Item>();
items.Add(new Item() { Id = 3, Name = "c" });
items.Add(new Item() { Id = 4, Name = "d" });
return View("MypartialView",items);
}
$(document).ready(function () {
var ajax_url = '#Url.Action("GetNewItems")';
$("#submit").click(function () {
$.ajax({
url: ajax_url,
type: "POST",
success: function (data) {
$("#div").html(data);
}
});
});
});
So, is it possible to pass the result to Partial view in success
function, or I have to manually render the elements in there?
you can solve this problem in couple of way -
use AJAXFORM Post.
Alternatively you can use JQuery templates.
JQuery Templates solution
First reference following JQuery libraries -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>
Then create the template which you want to fill up with details -
<script id="personsTmpl" type="text/x-jquery-tmpl">
<tr>
<th>${Name}</th>
</tr>
</script>
As a next step define the Table in html -
<table id="tableAttendees">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tr></tr>
</table>
Have a button on the page -
<input type="button" value="Click" onclick="submitForm()" />
Finally handle the JQuery Click event of the Submit button -
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("Submit")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: "Rami" }),
success: function (data) {
$("#personsTmpl").tmpl(data).appendTo("#tableAttendees");
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
When the button is clicked, Submit Action will be hit -
public ActionResult Submit(string name)
{
return Json(new Person() { Name = name + " Its Me" });
}
which would return person object -
public class Person
{
public string Name { get; set; }
}
Now when you run the application, and click on the button, you will see the values getting appending to the table as below -
Alternatively you can use AJAX form as shown below.
AJAXFORM Solution
Say you have Index as below -
#model MVC.Controllers.Person
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#using (Ajax.BeginForm("Submit", new AjaxOptions { UpdateTargetId = "productList" }))
{
<div>
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
</div>
<div>
<input type="submit" value="Add Product" />
</div>
}
<div id='productList'>
#{ Html.RenderPartial("itsme", Model); }
</div>
Which will hit Submit action and in turn we get a partial view -
public ActionResult Submit(Person p)
{
p.Name = p.Name + " Its me";
return PartialView("itsme", p);
}
And the partial view is simple which display the name -
#model MVC.Controllers.Person
#if (Model != null)
{
#Html.LabelFor(p => p.Name, Model.Name)
}
Finally the output -
If you don't want to return Partial View then you have to use a client side code to accomplish this. There are several options. You could review jTempaltes and jQuery Templates as an options. But if you won't call more than once this Ajax I would recommend you to return Partial View.

Categories

Resources