How to call .html.erb file on button click using .ajax call? - ruby-on-rails-3

function myCall() {
var request = $.ajax({
url: "new.html.erb",
type: "GET",
dataType: "html",
success:function(data) {
$("#mybox").html(data);
}
});
}
});
}
<input type="submit" name="submit" value="Create User" onclick="myCall();">
I have a page in that i created a button when i click that button i called a javascript function which open a form(available in new.html.erb file) in div tag which is in current page using ajax. I used the above method but nothing happens on button click.

Related

i want to call the controller by Ajax call butt how can i use JQUERY-UNOBTRUSIVE not using form tag

we can call the controller easily by using form tag like
<form asp-action="PartialAction" data-ajax="true" data-ajax-mode="replace" data-ajax-
update="#ProductList">
<input type="text" name="name" /><input type="submit" />
</form>
now i want to call action by using ajax. how can we use data-ajax , data-ajax-mode and data-ajax-updata attribute use in ajax call
var Categories = function (Key,Length) {
$.ajax(
{
type: "POST",
url: "/ShopGrid/PartialAction",
data: { GrpKey: array },
success: function (response) {
}
})
}
The effect of data-ajax,data-ajax-mode and data-ajax-update euqals to using .html() method in ajax success function:
success: function (response) {
$("#ProductList").html(response);
}
You can check the jquery-unobtrusive-ajax.js source code here:
https://github.com/aspnet/jquery-ajax-unobtrusive/blob/main/src/jquery.unobtrusive-ajax.js#L55

Render partial view on button click in asp.net core

Based on which button is clicked i want to render a partial View inside a div element.
If button1 is clicked then Partial View1 is rendered and if button2 is clicked then Partial View2
is rendered.
How can i do it.
Main View:enter code here
<button id="button1">One</button>
<button id="button2">Two</button>
<div id="search">
//Render Partial view here based on which button is clicked.
</div>
Partial View1:
<p>In Partial View1</p>
Partial View2:
<p>In Partial View2</p>
After i click the blue button, i want partial page to be rendered in Div area below the blue button. But its rendering above the button in grey area which is my common layout area.
Before click
enter image description here
After
enter image description here
I tried this code but the problem is that partial view is loading but not within the div element.
<input id="btnSearch" type="button" class="btn btn-primary" value="Search" />
<div id="students">
</div>
<script>
$('#btnSearch').on('click',
function (e) {
$.ajax({
url: '/Home/About',
type: 'POST',
cache: false,
async: true,
dataType: "html"
})
.done(function(result) {
$('#students').html(result);
}).fail(function(xhr) {
console.log('error : ' + xhr.status + ' - ' + xhr.statusText + ' - ' + xhr.responseText);
});
});
</script>
I think the code you posted should work, but you need to query the right endpoint of your home controller.
Given your minimal modified code (see the ajax url):
<input id="btnSearch" type="button" class="btn btn-primary" value="Search" />
<div id="students">
</div>
<script>
$('#btnSearch').on('click',
function (e) {
$.ajax({
url: '/Home/View2',
type: 'POST',
cache: false,
async: true,
dataType: "html"
})
.done(function(result) {
$('#students').html(result);
}).fail(function(xhr) {
console.log('error : ' + xhr.status + ' - ' + xhr.statusText + ' - ' + xhr.responseText);
});
});
</script>
And your HomeController.cs should have such a second method:
public IActionResult View2(){
return PartialView();
}
Edit I guess these pages could help you to get a rough idea of controllers and the handling:
Controllers and Endpoints:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/controller-methods-views?view=aspnetcore-3.0
Adding a search:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-3.0
But you are using a PartialView via jquery instead of returning a
full view.
Your search Method should end with return
PartialView(....)

Display mvc partial view with errors on parent page

I have a page with multiple forms, each as a partial. I want to post each partial on submit. If there are errors, I want the validation errors to show in the partial as part of the main page i.e. I don't want to just see the partial on it's own page if there are errors. Am I correct in saying this behavior is only possible with an ajax post? How would I return the model state errors WITHOUT an ajax post, just a normal form post?
Edit:
Still seeing the partial on it's own page
Partial -
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "LoginForm" }))
{
#Html.ValidationMessage("InvalidUserNamePassword")
<fieldset class="fieldset">
<div>
<label for="form-field-user_id">User ID</label>
<span>
#Html.TextBoxFor(x => x.Username, new { #class = "form-field__input form-field__input--text", #id = "form-field-user_id"})
</span>
</div>
</fieldset>
<div class="form-field__button">
<button id="loginButton" type="submit" class="button button--primary">Login</button>
</div>
}
<script>
$('#loginButton').click(function () {
$.ajax({
type: "POST",
url: '#Url.Action("Login", "Account")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
window.location.href = result.redirectTo;
} else {
$("#LoginForm").html(result);
}
},
error: function () {
$("#LoginForm").html(result);
}
});
});
</script>
Controller -
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (!ModelState.IsValid)
{
return PartialView("~/Views/Account/_Login.cshtml", model);
}
return Json(new { redirectTo = Url.Action("Index", "Profile") });
}
Yes, you are correct in saying this behavior is only possible with an ajax post.
There are a few problems with your current script meaning that you will not get the desired results.
Firstly your button is a submit button meaning that it will do a normal submit in addition to the ajax call unless you cancel the default event (by adding return false; as the last line of code in your script). However it would be easier to just change the button type to type="button"
<button id="loginButton" type="button" class="button button--primary">Login</button>
The ajax call will now update the existing page, however it will add the returned partial inside the existing <form> element resulting in nested forms which is invalid html and not supported. Change your html to wrap the main views form in another element
<div id="LoginFormContainer">
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "LoginForm" }))
{
....
<button id="loginButton" type="button" class="button button--primary">Login</button>
}
</div>
and then modify the script to update the html of the outer element
success: function (result) {
if (result.redirectTo) {
window.location.href = result.redirectTo;
} else {
$("#LoginFormContainer").html(result); // modify
}
},
Finally, your rendering dynamic content so client side validation will not work for the returned form. Assuming your properties have validation attributes (for example the [Required] attribute on the Userame property), you need to reparse the validator after loading the content
var form = $('#LoginForm');
....
} else {
$("#LoginFormContainer").html(result);
// reparse validator
form.data('validator', null);
$.validator.unobtrusive.parse(form);
}
You noted that you have multiple forms on the page, in which case your ajax options should be
data: $('#LoginForm').serialize(),
or if your declare var form = $('#LoginForm'); as per the above snippet, then data: form.serialize(), to ensure you are serializing the correct form.
Side note: There is no real need to change the id attribute of the textbox (it will be id=Username" by default and you can simply use
#Html.LabelFor(x => x.UserName, "User ID")
#Html.TextBoxFor(x => x.Username, new { #class = "form-field__input form-field__input--text" })
or just #Html.LabelFor(x => x.UserName) of the property is decorated with [Display(Name = "User ID")]

MVC4 View Multiple Submit Buttons - Update label text

At the moment I am working on a MVC4 view with multiple submit buttons. To handle the submit of the different buttons, I use this class:
http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx
I have three buttons and one label:
Start
Standby
Resume
How can I display a certain text in that label based on which button is pressed?
I wan to use Ajax.BeginForm to update the label text (so I do not have to reload the webpage).
Thank you in advance!
Update:
For example when I click at the Start Button a method will be executed. This method returns true or false. How to catch this bool and display text in the label, based on the result of the method?
Update 2:
<div>
<fieldset>
<legend>Admin Form</legend>
#Html.Label("Options")
<div id="StartBtn">
<input id="Start" type="submit" value="Start" name="action:Start" />
</div>
<div id="StandbyBtn">
<input id="Standby" type="submit" value="Standby" name="action:Standby" />
</div>
<div id="ResumeBtn">
<input id="Resume" type="submit" value="Resume" name="action:Resume" />
</div>
</fieldset>
</div>
[MultipleButton(Name = "action", Argument = "Start")]
public ActionResult Start()
{
if (start())
{
}
else
{
}
}
From your update I would use an ajax call instead of the ajax form
$('.btnSubmit').on('click', function(){
$.ajax({
url: '#Url.Action('Start', 'Controller')',
type: 'post',
data: {
button: this.id
}
dataType: 'json',
success: function(result){
if(result.Success){
$('.lblText').text(result.SetText);
}
}
});
});
I don't know what you want passed to your controller but if you put the same class on all of your buttons (you need to change them to type button instead of submit also) then this.id will will be the id of the clicked button and that will be sent to the controller
then on your controller have an input field matching what is in the data field
public ActionResult Start(string button){
//do something
//from here http://stackoverflow.com/questions/7732481/returning-json-from-controller-never-a-success
return Json(new { Success = "true", SetText = 'SetText' });
//Where SetText is whatever you want your label set to.
}
You can check on this post. http://www.developersnote.com/2013/02/multiple-button-in-mvc-4.html
#using (Html.BeginForm("ActionTaken", "TestController"))
{
<button name="button" value="ActionOne" class="button" style="width: 200px;">
test1</button>
<button name="button" class="button" style="width: 160px;" value="ActionTwo">
test2</button>
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ActionTaken(string butt)
{
string ButtCommand= butt;
switch (ButtCommand)
{
case "ActionOne":
//do stuff here
case "ActionTwo":
//do stuff here
default:
return View();
}
}

close modal form on ajax succes

i have a modal dialog conataining an ajax.beginform.
on a view i have a list of roles for a selected user, when i click add, the dialog is created using ajax
view:
<div id="popupAgregarRolModal" title="#Res_String.AsaignRol">
<!-- Client Partial, empty for now -->
</div>
<script>
$(document).ready(function () {
$(".AddRolButton").on("click", function (event) {
event.preventDefault();
$.ajax({
url: "Permiso/_GestionarRol?idSelectedUser=" + $("#AdmPerGridBUsquedaUsuarioSelectedRow").val(),
type: "GET",
})
.done(function (result) {
$("#popupAgregarRolModal").html(result).dialog({ modal: true, height: 'auto', width: 'auto', resizable: false });
});
});
});
function closeDialogNuevoRol(Result) {
$("#popupAgregarRolModal").dialog('destroy');
}
</script>
, the dialog contains an ajax.beginform like:
using (Ajax.BeginForm("SetPermiso", "Permiso", new AjaxOptions
{
UpdateTargetId = "ABMPermisos",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "closeDialogNuevoRol"
}, new { #id = "AddRolForm" }
)
)
{
.
.
.
the idea is that after i add a new rol to my user, the ajax target upload the list of roles on the view, this is done on my controler by using redirecttoaction if all comprobation and insertion logic hapends, then i whant to close the dialg but i only get
Uncaught Error: cannot call methods on dialog prior to initialization;
attempted to call method 'destroy'
To close a jQuery modal dialog, you can use this:
$("#popupAgregarRolModal").dialog("close");
Hope this helps.
EDIT: Try initializing the modal like this and not inside the click event of the button:
$(document).ready(function () {
$("#popupAgregarRolModal").dialog({ autoOpen: false, modal: true, resizable: false, draggable: false });
});
Then you can have a separate function for the click event.
$(".AddRolButton").click(function () {
//Do stuff
});
This post might help