so Iam new on this and I have a Ajax.ActionLink that work fine but can't understand (why I have to put the div "linkEdit" in my list view and in the partial view)
so have Ajax.ActionLink in my list view of solution (and when select a solution it get me all the product) and it goes to a action to
[HttpGet]
[Ajax(true)]
[ActionName("Index")]
public ActionResult Index_Ajax(Int32? id)
{
// to do = load the product that solution have
return PartialView("SolutionProduct", viewModel);
}
the Ajax.ActionLink
#Ajax.ActionLink("Select", "Index", "solution",
new { id = item.solutionId },
new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "linkEdit",
InsertionMode = InsertionMode.Replace
})|
i have this div in a partial view "SolutionProduct" and in my list view
<div id="linkEdit">
<table>
<tr>
<th>Nombre de Producto</th>
</tr>
#foreach (var item in Model.Productos)
{
<tr >
<td>
#item.Nombre
</td>
</tr>
}
</table>
}
</div>
so my question would be why if I take out the div on my list view it doesnt work?
I am going to share here different examples of using AJAX in ASP .NET MVC 4.
1) Use an Internet Application template to create ASP .NET MVC 4 project in Visual Studio 2012.
2) Under the folder Models create this simple class
public class Person
{
public string FirstName { set; get; }
}
3) Add following code to public class HomeController : Controller
[AcceptVerbs("POST")]
public bool MethodWithoutParameters()
{
bool allow = true;
if (allow)
{
return true;
}
else
{
return false;
}
}
[AcceptVerbs("POST")]
public string MethodWithParameters(string id)
{
return id + " i got it, man! ";
}
[AcceptVerbs("GET")]
public ActionResult GetSomeName()
{
var data = new { name = "TestName " };
return Json(data, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs("POST")]
public ActionResult PerformAction(FormCollection formCollection, Person model)
{
model.FirstName += "Well done! Form 1";
return Json( model.FirstName);
}
[AcceptVerbs("POST")]
public ActionResult PerformAction2(FormCollection formCollection, Person model)
{
model.FirstName += "Well don! Form 2";
return Json(model.FirstName);
}
public JsonResult DeleteFile(string fileName)
{
var result = fileName + " has been deleted";
return Json(result, JsonRequestBehavior.AllowGet);
}
4) Replace all code within Index.cshtml with the following one (Perhaps, instead of MvcApplication1 you have to use your real application name...)
#model MvcApplication1.Models.Person
#{
ViewBag.Title = "Home Page"; } #section featured {
}
MethodWithoutParameters
MethodWithParameters
'parameter00001'
#using (Ajax.BeginForm("PerformAction", "Home", new AjaxOptions {
InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess
= "OnSuccess", OnFailure = "OnFailure" })) {
This is a demo form1.
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, null, new { #class = "labelItem" })
}
#using (Ajax.BeginForm("PerformAction2", "Home", new AjaxOptions {
InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess
= "OnSuccess2", OnFailure = "OnFailure2" })) {
This is a demo form2.
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, null, new { #class = "labelItem" })
}
cat.png
Delete File
function DeleteFile() {
var fn = $('#fileNameLabel').html();
$.ajax({
url: "Home/DeleteFile", //check this.href in debugger
dataType: "text json",
type: "POST",
data: { fileName: fn }, //pass argument here
success: function (data, textStatus) {
if (data) {
if (textStatus == 'success') {
$('#fileNameLabel').html(data);
$('#btnDeleteFile').hide();
}
else {
alert('error');
}
} else {
alert('error');
}
}
});
}
function OnSuccess(response) {
$('#form1').html(response);
}
function OnFailure2(response) {
alert("Error Form 2");
}
function OnSuccess2(response) {
$('#form2').html(response);
}
function OnFailure(response) {
alert("Error Form 1");
}
function MethodWithoutParameters() {
var url = "Home/MethodWithoutParameters";
$.post(url, function (data) {
if (data) {
alert(data);
} else {
alert('error');
}
});
}
function MethodWithParameters(id) {
var url = "Home/MethodWithParameters/" + id;
// alert(url);
$.post(url, function (data) {
if (data) {
alert(data);
} else {
alert('error');
}
});
}
$(document).ready(function () {
$.getJSON("Home/GetSomeName",
null,
function (data) {
if (data) {
$('#UserNameLabel').html(data.name);
} else {
alert('error');
}
}
);
}); </script>
5) Make sure that header of the _Layout.cshtml looks like
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"
type="text/javascript">
6) And everything should work fine.
I hope all those samples will help you!
You have to put the div with an id of "linkEdit" into your list view as that is the portion of the page that is to be replaced by the result returned by the ajax link.
ASP.NET AJAX enables a Web application to retrieve data from the server asynchronously and to update parts of the existing page. This improves the user experience by making the Web application more responsive.
And is this case you are using the InsertionMode
InsertionMode = InsertionMode.Replace
so you will need a div with the id of "linkEdit" in both your list view and partial view.
Related
I have this C# method:
C#
[HttpPost]
[AllowAnonymous]
public JsonResult PostOnCRM(string textBoxFirstName, string textBoxCountry, string textBoxLastName, string textBoxEmail, string textBoxTitle, string textBoxTelephone, string textBoxCompany, string textBoxWebsite, string textAreaNote, string checkBoxUpdates)
{
bool isValidEmail = Regex.IsMatch(textBoxEmail,
#"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
if (!isValidEmail)
throw new Exception("E-mail is not a valid one");
LeadInformation lead = new LeadInformation()
{
Subject = "Web site",
FirstName = textBoxFirstName,
LastName = textBoxLastName,
JobTitle = textBoxTitle,
Address1_Country = textBoxCountry,
EmailAddress1 = textBoxEmail,
MobilePhone = textBoxTelephone,
WebsiteUrl = textBoxWebsite,
Description = textAreaNote,
DoNotEmail = checkBoxUpdates.Contains("Yes") ? true : false
};
//Some method that works well go here
return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
And in my view, this Ajax call
Ajax
$("#formContact").submit(function (evt) {
evt.preventDefault();
var formdata = $('form').serialize();
$.ajax({
type: 'POST',
dataType: "json",
cache: false,
url: 'http://localhost:59289/Lead/PostOnCRM',
data: formdata,
success: function (response) {
alert('success!');
},
error: function (response) {
alert('Error! try again later');
}
});
});
The method performs perfectly. Does the insert in the database but when it returns to the ajax method it always lands on the 'error' and does not return the response I've sent. What can it be?
Sorry for taking the parameters in this way (especially bool value thing) and for not use a Bind or anything, but this is not relevant to the question
I asked it at Portuguese StackOverflow but without a good answer.
Here, a print of my browser
https://postimg.cc/image/e86q3hcol/
First of all, you should never use Regular Expression to validate email address. Look at this.
Second, you want to use Model in ASP.Net MVC, instead of declaring multiple parameters in action method.
Please do it property. If you still have question, please come back and ask again. Here is a working example -
View
#model UserModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
#using (Html.BeginForm())
{
#Html.TextBoxFor(model => model.Email)
<button id="btnSubmit" type="button">Submit</button>
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function () {
$("#btnSubmit").click(function () {
var data = {
Email: $("#Email").val()
};
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "#Url.Action("PostOnCRM", "Lead")",
data: JSON.stringify(data),
success: function (response) {
alert('success!');
},
error: function (response) {
alert('Error! try again later');
}
});
});
});
</script>
</body>
</html>
View
public class UserModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Country { get; set; }
public string Email { get; set; }
}
Controller
public class LeadController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public JsonResult PostOnCRM(UserModel model)
{
bool isValidEmail = IsValidEmail(model.Email);
if (!isValidEmail)
throw new Exception("E-mail is not a valid one");
// ...
return Json(new { success = true, responseText = "Your message successfuly sent!" });
}
public static bool IsValidEmail(string email)
{
if (String.IsNullOrWhiteSpace(email))
return false;
try
{
email = new MailAddress(email).Address;
return true;
}
catch (FormatException)
{
return false;
}
}
}
My boss resolved my problem in 5 minutes (i tried by 2 days) with
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
On web.config :|
I don't know why. Some one can explain me?
I Forgot to say but it's a cross origin request :|
I'm a beginner & I'm trying to develop a autocomplete search box with ASP.Net MVC 5. I use Northwind Database and Entity Framework 6.
Here is my index.cshtml code
#model IEnumerable<AutoComplete3.Models.Customers>
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("GetCustomers")'
});
});
</script>
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Here is my CustomerController class
public class CustomersController : Controller
{
northwindEntities db = new northwindEntities();
public ActionResult Index()
{
return View(db.Customers);
}
[HttpPost]
public ActionResult Index(string SearchTerm)
{
List<Customers> customers;
if (string.IsNullOrEmpty(SearchTerm))
{
customers = db.Customers.ToList();
}
else
{
customers = db.Customers.Where(c => c.CompanyName.StartsWith(SearchTerm)).ToList();
}
return View(customers);
}
public JsonResult GetCustomers(string term)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
}
This code is working when i am searching records, by entering keyword & clicking submit button. But the GetCustomer method cannot be called by the jquery script. Inspect Elements shows following error.
Uncaught TypeError: $(...).autocomplete is not a function
The text box should be suggest Company Names to the textbox itself. How to correct this.
Thanks.
Javascript
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetCustomers","Home")',
type: "POST",
dataType: "json",
data: { searchTerm: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CompanyName, value: item.CompanyName };
}))
}
})
},
messages: {
noResults: "", results: ""
},
});
})
View
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Controller
Please update your controller with [HttpPost]
[HttpPost]
public JsonResult GetCustomers(string searchTerm)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
I was working to use Kendo Grid in asp.net mvc4.Here is the code written in contrller and view.But i am not getting the Kendo Grid in output.Can anyone help me with this?
I have used ADO.NET entity model to form class called Contacts to connect to the database
and in the controller i have converted the data coming from Contacts class to json.
Controller:
public class HomeController : Controller
{
public PersonaEntities db = new PersonaEntities();
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[HttpGet]
public JsonResult Getjsondata()
{
ViewBag.Title = "Hello World";
JsonResult jsonResult = new JsonResult();
var Contacts = db.Contacts.ToList();
jsonResult.Data = Contacts;
return Json(jsonResult,JsonRequestBehavior.AllowGet);
}
Then i have tried in the view to display kendo grid by giving its datasource as controller action method.But I am not getting the output as kendo grid.
View:
#{
ViewBag.Title = "Getjsondata";
}
<h2>Getjsondata</h2>
<link href="~/Content/kendo/2014.2.716/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.dataviz.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/2014.2.716/angular.min.js"></script>
<script src="~/Scripts/kendo/2014.2.716/jquery.min.js"></script>
<script src="~/Scripts/kendo/2014.2.716/kendo.all.min.js"></script>
<script>
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: { read: { url: "Home/Getjsondata", dataType: "json" } },
schema: {
data: function (data) {
return data;
}
}
})
$("#Grid").kendoGrid({
dataSource: dataSource,
columns: [
{
field: "id",
title: "id"
},
{
field: "fname",
title: "fname"
},
{
field: "lname",
title: "lname"
},
{
field: "phone",
title: "phone"
}
]
});
});
</script>
<div id="Grid"></div>
The Json method encapsulated the data into a JsonResult already. Your reposonse is double-wrapped. Pass the data directly into the Json method.
You'll need two actions, one for the static view and one for the JsonResult:
public class HomeController : Controller
{
public ActionResult GridView()
{
return this.View();
}
public JsonResult Getjsondata()
{
var Contacts = db.Contacts.ToList();
return Json(Contacts, JsonRequestBehavior.AllowGet);
}
}
For the view, you need a GridView.cshtml:
#* css and js imports omitted *#
<script>
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: '#Url.Action("Getjsondata")',
type: 'GET', // should be POST, though
}
},
schema: {
type: "json",
model: {
id: "id",
fields: {
'id' : { type: 'number', editable: false},
'fname': { type: 'string' },
'lname': { type: 'string' },
'phone': { type: 'string' }
}
}
}
},
columns: [
{
field: "id",
title: "id"
},
{
field: "fname",
title: "fname"
},
{
field: "lname",
title: "lname"
},
{
field: "phone",
title: "phone"
}
]
});
});
</script>
<div id="Grid"></div>
The url of the page is ~/Home/GridView. When you open the page, the controller only returns the static page GridView.cshtml. Once the page is loaded on the client side (your browser), the JavaScript code will run and make an AJAX request to the ~/Home/Getjsondata action to load the data for the kendo grid.
I found out that i was loading the script jquery.js manually which i think gets loaded by default in browser.Also i found that scripts and css files need to be mentioned only in shared layout file and not necessary to mention it in view.
jquery asp.net-mvc
I am doing a web application using ASP.NET MVC 5. It seems to me that I did everything as it goes, but ajax is just not working. I see results only after refreshing.
This is in my View:
#{
AjaxOptions ajaxOptions = new AjaxOptions {
UpdateTargetId = "CommmentList",
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace};
}
<div id="CommentList">
#using (Ajax.BeginForm("Index", "Comment", ajaxOptions))
{
// some content
<div>
#Html.Action("_AddCommentForItem", "Comment")
</div>
}
</div>
This is in a layout view:
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
EDIT:
These are actions in a Comment controller:
// GET: Comment
public async Task<ActionResult> Index()
{
var comments = db.Comments.Include(k => k.Item);
return View(await comments.ToListAsync());
}
// GET
public PartialViewResult _AddCommentForItem()
{
ViewBag.ItemId = new SelectList(db.Items, "Id", "Name");
return PartialView("_AddCommentForItem");
}
// POST
[HttpPost]
public PartialViewResult _AddCommentForItem ([Bind(Include = "Id,ItemId,CommentContent")] Comment comment)
{
if (ModelState.IsValid)
{
db.Comments.Add(commment);
db.SaveChanges();
}
ViewBag.ItemId = new SelectList(db.Items, "Id", "Name", comment.ItemId);
return PartialView("_AddCommentForItem");
}
}
}
I included partial view _AddCommentForItem, which is creating a comment, in an index view of the Comment controller. That's way i want the result to be visible right away, without refreshing.
What am I missing?
Thank you.
Given these C# objects
class foo
{
int fooId {get; set;}
string fooName {get;set;}
List<bar> bars {get; set;}
}
class bar
{
int barId {get; set;}
string barName {get;set;}
}
and a WebApi method
[HttpPost]
public HttpResponseMessage AddFooBar(foo model)
{
//...
}
Assuming we have a form where a user enters fooName and a list of bar items, what is the best way to serialize the data from the form and submit it to the WebApi method?
I strongly recommend simply creating a dumb view with
<form id="f">
#Html.TextBoxFor(x=>x.foo);
#for(var i = 0; i<Model.foo.bars.Length; i++){
#Html.TextBoxFor(x=>x.foo.bars[i]);
}
</form>
$(document).ready(function(){
console.log($('#f').serialize());
});
So you can see the structure expected. Then You can fill your JSON how you wish
I could not find a way to post foo and list of bars in one ajax call and into one WebApi controller action. I ended with two ajax posts and two controller actions. Two trips instead of one but it works. Below is my solution in case anyone may find it useful.
On the html side, I used two divs for the forms since this is Asp.net webforms which means we are limited to one form.
<div id="foo-form">
<input type="text" name="fooName" value="" />
<button type="button" class="btn-cancel">Cancel</button>
<button type="button" class="btn-submit">Submit</button>
</div>
<div id="bar-form">
<input type="text" class="foobar" value="" />
<input type="text" class="foobar" value="" />
<input type="text" class="foobar" value="" />
<input type="text" class="foobar" value="" />
</div>
Javascript side (with Jquery ajax)
$("#foo-form .btn-submit").click(function (e) {
e.preventDefault();
fooBar.saveFoo();
});
var fooBar = new function () {
//this posts foo
this.saveFoo = function () {
// serialize the form
var serializedData = $("#foo-form :input").serialize();
$.ajax({
type: "POST",
url: "/myapp/api/FooBar/AddFoo",
data: serializedData,
cache: false
}).done(function (data) {
if (data["Status"] === 'success') {
//pass the id to the saveBars function
fooBar.saveBars(data["Id"])
}
else {
//handle logic error
}
}).fail(function (xhr, textStatus, errorThrown) {
//handle ajax error
}).always(function () {
//something to do always
});
}
//this posts bars
this.saveBars = function (fooId) {
//save all bars in array
var arrBars = [];
$('#bar-form .foobar').each(function () {
arrBars.push(
{
"fooId": fooId,
"fooName": $(this).val()
}
);
});
$.ajax({
type: "POST",
url: "/myapp/api/FooBar/AddBars",
data: JSON.stringify(arrBars),
cache: false,
contentType: "application/json; charset=utf-8"
}).done(function (data) {
if (data["Status"] === 'success') {
//show success message
}
else {
//handle logic error
}
}).fail(function (xhr, textStatus, errorThrown) {
//handle ajax error
}).always(function () {
//something to do always
});
}
}
And now on the server side webapi controller C# code
[HttpPost]
public HttpResponseMessage AddFoo(Foo model)
{
try
{
//validate
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "error", Message = "Error in foo"});
//save foo
var db = new FooBarDB();
var id = db.AddFoo(model);
//return new fooId
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "success", Id = id });
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[HttpPost]
public HttpResponseMessage AddBars(List<Bar> bars)
{
try
{
//validate bars
if (!this.ValidateBars(bars))
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "error", Message = "Errors in bars"});
//save bars
var db = new FooBarDB();
db.AddBars(bars);
//show success
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "success"});
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
private bool ValidateBars(List<Bar> bars)
{
//logic to validate bars
}