I have this issue with autocomplete, it returns something like this:This
But when you check what returns post method everything is as it should be but in view we get in return just blank field, instead of word "Hardware".
My Code:
Constructuor Method:
[HttpPost]
public JsonResult CreateJS(string prefix)
{
List<CategoryModel> list = new List<CategoryModel>();
list = _context.Categories.ToList();
var CatList = (from N in list
where N.Name.StartsWith(prefix)
select new { value = N.Name,label = N.Name });
return Json(CatList);
View:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#Category").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Incident/CreateJS",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="IncidentDescription" class="control-label"></label>
<input asp-for="IncidentDescription" class="form-control" />
<span asp-validation-for="IncidentDescription" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Category">Cat:</label>
<input type"text" name="Category" id="Category"/>
</div>
There is no need to use $.map in the ajax callback functiom. Directly apply the data to the response.
<script>
$(document).ready(function () {
$("#Category").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Incident/CreateJS",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
});
})
</script>
Related
I am using C# and ASP.NET MVC and try to pass data from the controller to the view. When I debug data show in viewbag but not show in view. The error is undefined. I don't know why this code shows an error.
This is the screenshot:
Screenshot of Debug Result
C# code:
public JsonResult mselectCOACodes(string gl_code)
{
ViewBag.mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (ViewBag.mainCode != "")
{
ViewBag.mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json("", JsonRequestBehavior.AllowGet);
}
jQuery:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
View
<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode"
value="#ViewBag.mainCode" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription"
value="#ViewBag.mainDesc" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
Firstly, don't use #ViewBag to store the input value, because you cannot access its value inside your C# code.
Here is C# code:
public JsonResult mselectCOACodes(string gl_code)
{
string mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (mainCode != "")
{
string mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json(mainDesc, JsonRequestBehavior.AllowGet);
}
Here is JQuery:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (mainDesc) {
$("#txtmainDescription").val(mainDesc);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
View:
<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode"
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription"
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
Im trying to change a "name" textbox color to (blue if it is male, and pink if it is female) after changing a "gender" dropdown in a partial view.
Index View:
#{
ViewData["Title"] = "Home Page";
var gender = ViewBag.Gender; //breakpoint
}
#if (gender == "Male")
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: lightblue" />
</div>
}
else if (gender == "Female")
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: lightpink" />
</div>
}
else
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: white" />
</div>
}
<div id="gender">
<partial name="_GenderDropdown" model="Model" />
</div>
Partial View:
<label>Gender</label>
<select id="genderstring">
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
//ajax for posting gender to controller
$('#genderstring').on('change', function () {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
data: { gender: $("#genderstring").val() },
success: function () {
},
error: function () {
}
});
});
});
</script>
Controller:
public IActionResult Index(string gender)
{
if(gender == null)
{
return View(new User { Name = "", Gender = "" });
}
else
{
ViewBag.Gender = gender;
return View("Index"); //breakpoint
}
}
With this 2 breakpoints i can see that the data is passing but after I change the gender it gets to the view with the gender in the viewbag but the rest of the page doesen't run.
When you use ajax,it would not reload your page after backend code finishing by default.More detailed explanation and solution you could check as follow:
The first way
You could use .html() method to render the backend result to html after ajax success:
1.View(Be sure add a div to contain the whole html):
<div id="result"> //add the div......
#if (gender == "Male")
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: lightblue" />
</div>
}
else if (gender == "Female")
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: lightpink" />
</div>
}
else
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: white" />
</div>
}
<div id="gender">
<partial name="_GenderDropdown" model="Model" />
</div>
</div>
2.Js in partial view:
<script>
$(document).ready(function () {
$('#genderstring').on('change', function () {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
data: { gender: $("#genderstring").val() },
success: function (res) {
$("#result").html(res); //add this...
},
error: function () {
}
});
});
});
</script>
3.Controller:
You need return PartialView instead of returning View,because if you return view it will generate the layout(e.g the nav bar) again(you could have a try by yourself).
[HttpGet]
public IActionResult Index(string gender)
{
if (gender == null)
{
return View(new User { Name = "", Gender = "" });
}
else
{
ViewBag.Gender = gender;
return PartialView("Index"); //change here...
}
}
Result:
The second way
You could avoid using ajax,just use window.location.href to reload the page(The view and controller are the same as yours,do not change like the first way):
<script>
$(document).ready(function () {
$('#genderstring').on('change', function () {
window.location.href = "/Home/Index?gender=" + $("#genderstring").val();
});
});
</script>
Result:
Note:
If you want to maintain the select list selected item,you may choose the first way,and modify your js like below:
<script>
$(document).ready(function () {
//ajax for posting gender to controller
$('#genderstring').on('change', function () {
var selected_item = $("#genderstring").val(); //add this ....
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
data: { gender: selected_item },
success: function (res) {
$("#result").html(res);
$("#genderstring").val(selected_item); //add this....
},
error: function () {
}
});
});
});
</script>
Result:
I need to create a newsletter form in my footer, so I had to include it in my layout.
I have successfully created the form using:
<footer>
<form method="post" asp-controller="NewsletterSubscriptions" asp-action="Create" data-ajax="true" data-ajax-method="post" data-ajax-success="success" data-ajax-completed="completed">
<div class="newsletter" id="newsletter">
<div class="form-group">
<input type="text" id="FullName" name="FullName" data-provide="FullName" class="form-control" placeholder="name" autocomplete="off">
</div>
<div class="form-group">
<input type="email" id="Email" name="Email" data-provide="Email" class="form-control" placeholder="email" autocomplete="off">
</div>
</div>
<div class="newsletter-btn">
<input type="submit" value="ok" />
</div>
</form>
</footer>
And in Head:
<head>
<script src="#Url.Content("/lib/jquery-validation/dist/jquery.validate.js")"></script>
<script src="#Url.Content("/lib/jquery-validation/dist/additional-methods.js")"></script>
<script src="#Url.Content("/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js")"></script>
<script>
success = function () {
alert("Hi !");
};
</script>
<script>
completed = function (xhr) {
alert("Hi ${xhr.responseText}!");
};
</script>
</head>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("FullName,Email")] NewsletterSubscription newsletterSubscription)
{
if (ModelState.IsValid)
{
_context.Add(newsletterSubscription);
await _context.SaveChangesAsync();
return Redirect(Request.Headers["Referer"]+ "#newsletter");
}
else
return View(newsletterSubscription);
}
When I submit, page is refreshed, form is submitted successfully, user is redirected to same page footer area.
But success, or completed functions are not triggered. what am I doing wrong?
Write your form tag as follows:
<div id="success-message-container" class="alert alert-success text-center d-none">
<strong>Success!</strong> You have been subscribed successfully!
</div>
<div id="failure-message-container" class="alert alert-danger text-center d-none">
<strong>Failure!</strong> There is some problem with the service.Please try again.If the problem persists
please contract with system administrator!
</div>
<form id="newsLetterForm" method="post" asp-controller="NewsletterSubscriptions" asp-action="Create">
// Your form contents
</form>
Then in the JavaScript :
$(document).on("submit", "#newsLetterForm", function (event) {
event.preventDefault();
event.stopImmediatePropagation();
var formData = new FormData(this);
var url = this[0].action; // if this does not work then use '#Url.Action("Create","NewsletterSubscriptions")'
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (response) {
if (response) {
document.getElementById("newsLetterForm").reset();
$("#newsLetterForm input,textarea").removeClass('valid');
$("#success-message-container").removeClass("d-none");
setTimeout(function () {
$("#success-message-container").addClass("d-none");
}, 5000);
}
},
error: function () {
$("#failure-message-container").removeClass("d-none");
setTimeout(function () {
$("#failure-message-container").addClass("d-none");
}, 5000);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Note: css classes I have used is from Bootstrap 4
I am trying to send the value of <textarea> to a method in some controller but doesn't run well. I will post the code to make it clear:
Here is the method
public ActionResult SubmitText(string txtRendered)
and here is the ajax to call
$.ajax({
url: '/Form/SubmitText',
type: 'Get',
dataType: 'json',
data: { txtRendered: $("textarea#render").val() },
success: function (data) {
alert("success");
},
error: function () {
alert('error');
}
});
and here is the textarea
<textarea id="render" name="txtRenderd" class="span6">
<form class="form-horizontal" >
<fieldset>
<legend>Form Name</legend>
<div class="control-group">
<label class="control-label" for="textinput-0">Text Input</label>
<div class="controls">
<input id="textinput-0" name="textinput-0" type="text" placeholder="placeholder" class="input-xlarge">
<p class="help-block">help</p>
</div>
</div>
</fieldset>
</form>
</textarea>
actually it is complicated, since I am trying to pass a form as a text as you can see
I'm trying to learn MVC and one the things I want to do is submit a form to an action in my controller and this action will return the submitted data. Sounds simple but I've been trying for hours without any success.
my view:
#using (Html.BeginForm("BlogComment","Blog"))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
my controller:
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
mRep.Add(ajaxComment);
uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
and my js:
$(document).ready(function () {
$('form').submit(function () {
$.ajax({
url: '#Url.Action("CommentForm")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
You don't need to write any client side code to do this, FYI.
To use the ajax methods successfully in MVC, you will need to do the following. Add this key to appsettings in web.config:
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
As well as include the unobtrusive ajax script:
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
Then create div container around your form and replace Html.BeginForm with Ajax.BeginForm
<div id="ajaxReplace">
#using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" }))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
</div>
Then in your controller you'll return something like this:
return PartialView(ajaxComment);
This will save you maintaining a script to do this manually and will funnel you into using the framework as intended. It will also help you out with data annotation validation and all of the juicy stuff that goes with it,
I hope this helps in some way.
Try this:
The Model
public class Comment
{
public string CommentText { get; set; }
public DateTime? DateCreated { get; set; }
public long PostId { get; set; }
public string UserName { get; set; }
}
The View and js
#model SubmitMvcForWithJQueryAjax.Models.Comment
#using (Html.BeginForm("BlogComment","Blog"))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
#Html.EditorFor(m => m.UserName)
</div>
<div class="editor-text">
#Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"} )
</div>
<div class="editor-field">
#Html.HiddenFor(m => m.DateCreated)
</div>
<div class="editor-field">
#Html.HiddenFor(m => m.PostId)
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function () {
var serializedForm = $(this).serialize();
$.ajax({
url: '#Url.Action("CommentForm")',
type: "POST",
data: serializedForm,
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
</script>
The Controller
public class CommentController : Controller
{
//
// GET: /Comment/
public ActionResult Index()
{
return View(new Comment());
}
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated ?? DateTime.Now;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
//mRep.Add(ajaxComment);
//uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
}
Basically you are passing javascript object literals directly. So, before you pass data to your controller, it must be in JSON format(because you have specified application/json. see your $.ajax call).
SO, you are missing JSON.stringify()
data: JSON.stringify({
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
}),
OR
var someObj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
/// your other code
data: JSON.stringify(someObj),
// your rest of the code
});
Instead of
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
Try
$('form').submit(function () {
var obj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
...,
data: JSON.stringify(obj),
...,
});
return false;
});
You have to convert data to string before sending it to server. and JSON.stringify does that job