I have a partial view which contains a list of elements, to which i add a new element without limit, but when i add a field. It pops the validation for all the other fields of the list.
For example if i leave a field empty and call the controller and get the partial view back, the required error is poped for that field.
How can i avoid this case and pop validations only if they were poped before the post?
The id=5 is just for test purposes
I have a call to the controller like this
public ActionResult AddDestination(List<Destination> model)
{
model.Add(new Destination(){id = 5});
return PartialView("_FieldDestination", model);
}
AJAX Call:
function addField(event) {
debugger;
event.preventDefault();
var model = $("#multipleDestinations:input").serialize();
$.ajax({
type: 'POST',
url: '#Url.Action("AddDestination", "Controller")',
data: model,
success: function (data) {
debugger;
$("#multipleDestinations").html(data);
}
, error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);}
});
}
Related
How you doing? I hope its good.
I have a "View" called Create and another two "partial" "views", a view is used to render a bootstrap modal and other to render a table, when I do a post in this modal I must to update that table, but when the model state of the modal is invalid I must call his action, how can I do this? I tryed to use return PartialView("ModalProduto", model);
try something like this
function () {
$.ajax({
url: URL/PartialViewAction,
type: 'GET',
data: $(form1.).serialize(), // or make your objects for the partial
success: function (data) {
$("#placeforthepartialview_as_a_modal").html(data);
},
error: function (e, data) {
}
});
});
im trying to get the value each time a client selects a option from my Dropdown list to send it back to controller where i use the value on creating a file and then refreshing the page but im unable to do so
This is my Dropdownlist:
<select id="sel0">
<option value="">Todos</option>
#foreach (var item in Model.Select(l => l.Fecha).Distinct())
{
<option value="#lines">#lines</option>
}
</select>
This is my Ajax Call:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
});
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
and this is my Controller its named 'HomePosController':
public ActionResult MethodName(string Selected)
{
var db = new ArponClientPosContext();
String value = Selected;
var json4 = JsonConvert.SerializeObject(Selected);
System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\potzolcalli.brain.arpon.com\valorselected.txt", json4);
return View("~/Views/HomePos/Index.cshtml", db.Pos.ToList());
}
But whenever y select a option of my dropdown nothing happens, the page its not refreshed nor the file is created what am i doing wrong?
If you want it to be on dropdown change then you have to send ajax call in change event :
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePos")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
and you have to not write complete Controller class name, you have to skip the Controller postfix, it is convention which is followed by Url helpers in mvc, that way your url generated will be wrong and ajax call will fail.
whenever y select a option of my dropdown nothing happens
Well, this happens:
dataTable.columns('.fechas').search(this.value).draw();
But that doesn't invoke the AJAX request. It doesn't do much of anything, really.
how can i trigger the ajax ? i want it to trigger after a value is changed in the dropdown list
In that case you want to do that on the select element's change event. Currently you perform the AJAX request here:
$("form").submit(function () {
// AJAX
});
That is, you perform the request in the form's submit event. Just add it to the drop down's change event instead:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
the page its not refreshed
Well, no. That won't happen in an AJAX request. Currently your success callback is empty, so nothing will happen on the page. Whatever you want to happen would need to be put in that callback.
I have a json data object which i need to pass from partial view to view with REDIRECT.
Lets say below is my partial view ( _createEmp.cshtml ):-
Note:- This partial view is in different view or page
<script type="text/javascript">
$(document).ready(function () {
LoadData();
});
function LoadData() {
$.ajax({
type: "GET",
url: baseURL + "Employee/GetEmpInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
**EmpData** = data; // EmpData object
},
error: function (error) {
console.log("Error: " + error);
}
});
}
</script>
<div>
<input type="submit" value="Save" onclick="SetEmpInfo()" />
</div>
And i want to transfer EmpData object to a different view (lets say NewEmp.cshtml), bind something in that view from passed "EmpData object" and open that view (or REDIRECT to view NewEmp.cshtml).
As you are using ajax, you could return the URL from your action and have it redirected in javascript.
Without seeing your controller action you would need to do something like this:
Controller
public ActionResult GetEmpInfo()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("GetEmpInfoSuccess") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (data) {
if (data.success == true)
{
window.location = result.redirecturl;
}
}
Issuing a request to Employee/GetEmpInfo for getting the data and on success redirecting to other view - doesn't sound right
I think that you can do all this with one trip to server:
Write an Action that receives all the the parameters that GetEmpInfo receives. Lets call it NewEmployee.
If GetEmpInfo action is your code, reuse it's logic inside NewEmployee action to get EmpData. If it is not your code, you can use issue async request with HttpClient and get EmpData - All this performed on the server
Once you have EmpData you should have everything your need to return a NewEmp view.
In this particular case there is no need in AJAX at all. You can use regular form submit in case that you need to post some data or just a redirect to NewEmployee action.
I have a webform with few textboxes and dropdownlists, and a submit button
when the user clicks the submit button im sending the form values to the controller with an ajax call and from controller to model to database
after submitting the form values are still being displayed in the respective textboxes.
i also have a output parameter with my procedure, if the data is successfully submitted then i will get output parameter value as 1 else 0
so based on this output parameter value from the controller i should be able to clear the form values, if the insertion fails the values should be displayed
how to achieve it?
<script type="text/javascript">
function CreateUser() {
$.ajax({
url: '#Url.Content("~/User/CreateUser")',
data: { My Data },
type: 'GET',
success: function (data) {
alert(data);
}
});
}
$('#btnCreate').click(function () {
CreateUser();
});
</script>
Code:
public ActionResult RegisterUser(Users objUser)
{
//i have done some code here to bind dropdownlists from database etc
return View(objUser);
}
public ActionResult CreateUser(str Uname)
{
try
{
Users objUser = new Users();
int Successval = objUser.CreateUser(Uname);
}
catch (Exception ex)
{
}
return RedirectToAction("RegisterUser");
}
try this ...
after you get value 0 then just call below line
document.getElementById("YOUR_FORM_ID").reset();
Update
View :
<form id="myform">
...
</form>
Javascript :
function CreateUser() {
$.ajax({
url: '#Url.Content("~/User/CreateUser")',
data: { My Data },
type: 'GET',
success: function (data) {
if(data == 0)
{
document.getElementById("myform").reset();
}
}
});
}
I have a controller action which is getting called by JQuery ajax, and hopefully returniung the contents of "Results" to the requesting page.
So far I have...
Controller
public ActionResult DynCalc(resultsModel model){
...
//code that populates model - all working ok
...
if (Request.IsAjaxRequest())
{
return PartialView("results", model.Results);
}
else
{
return null; //Handle this later
}
}
This passes back a valid model.
Called from the javascript:
$.ajax({
url: "/Test/DynCalc",
type: "POST",
data: $("#frmResults").serialize(), //This part works
dataType: "html",
success: function (result) {
$('#resultsSection').html(result);
$('#hide_panel a').flash("#111", 1000);
}
});
Sucess is never hit. Hopefully somebody can just tell me i'm being daft and missing something obvious?
My partial view results is just a HTML page with javascript on it. If I just have the following
Hello world in my results view, then it works ok, with any script in, it doesn't
Am I on the right track? Should I be changing the type of return on the controller? Or using JSON?
I didn't post the contents of the results page, as It doesn't matter if it's a whole document or simply <b>hi</b> - it does the same thing.
Try to return just a View. Because your result in this case is a complete View (because the action result could be HTML, XML, JSON...whatever).
Use PartialView only as a way to render part of your View.
E.g. on your MasterPage you would like to "always" render user info: #RenderAction("UserInfoAction", "UserController")
var model= {
"PropertyName1":$("#txt1").val(),
"PropertyName1": $("#txt2").val(),
}
$.ajax({
type:"POST",
url: 'Url.Action("DynCalc","ControllerName")',
data: JSON.stringify(model),
contentType: "application/json;charset=utf-8",
success: function (data, status, xhr)
{
alert("The result is : " + status + ": " + data);
},
error: function (xhr)
{
alert(xhr.responseText);
}
});