Viewbag value not show in ASP.NET MVC view - c#

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>

Related

Jquery Autocomplete blank field

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>

Submitting a post form with success message from Layout in Asp.Net core

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

Post textarea value to controller using ajax

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

How to call user control method using jQuery AJAX in Asp.Net

Here is the acsx page.
I have two drop down in Bootstrap modal (State and City).
Based on the state selection, City dropdown should populate option.
I have created two methods in code behind for state FillStatedata() and for city getCitydata().
I need to call getCitydata() method on state selection change using jQuery AJAX and then bind the city data with city drop down.
I am getting Statename on state change but not able to executive getCitydata() method using statename as parameter.
Why?
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Registeration.ascx.cs" Inherits="WebApplication1.UserControl.Registeration" %>
<%# Import Namespace = "System.Web.Security" %>
<script src="~/scripts/jquery-1.10.2.js"></script>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<!--jquery start here-->
<script>
$(document).ready(function () {
var getSelState;
$("#State").change(function () {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: alert("{'Statename':'" + $('#State').val() + "'}"), //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) { //handle the callback to handle response
//request was successful. so Retrieve the values in the response.
}
})
});
});
</script>
<input type="hidden" id="myhiddenField" name="myhiddenField" value="" ClientIDMode="Static" runat="server" />
<div class="form-horizontal" role="form" runat="server">
New User?
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Register</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="full-name" class="col-sm-2 control-label">FullName:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="full-name">
</div>
</div>
<div class="form-group">
<label for="User-Name" class="col-sm-2 control-label">Username:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="User-Name">
</div>
</div>
<div class="form-group">
<label for="Create-Password" class="col-sm-2 control-label">Create Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Create-Password">
</div>
</div>
<div class="form-group">
<label for="confirm-Password" class="col-sm-2 control-label">Confirm Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Confirm-Password">
</div>
</div>
<div class="form-group">
<label for="Mobile-Number" class="col-sm-2 control-label">Mobile No:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Mobile-Number">
</div>
</div>
<div class="form-group">
<label for="State" class="col-sm-2 control-label">State:</label>
<div class="col-sm-10">
<select class="form-control" id="State" runat="server" ClientIDMode="Static">
</select>
</div>
</div>
<div class="form-group">
<label for="City" class="col-sm-2 control-label">City:</label>
<div class="col-lg-10">
<select class="form-control" id="City" runat="server" DataTextField="Cityname"
DataValueField="Cityname"></select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-primary">Cancel</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
First things first.
just use one library either min for prod or non min for dev.
data:{} should have to be an object or string value.
use one of it:
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var getSelState;
$("#State").change(function() {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: "{'Statename':'" + this.value + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) { //handle the callback to handle response
console.log(msg);
}
});
});
});
</script>
function getCitydata()(obj) {
var ddlcity = document.getElementById('<%= ddlcity.ClientID %>');
ddlcity.innerHTML = '';
$.support.cors = true;
var serviceUrl = '/ashx/map/Address.ashx';
if (serviceUrl.indexOf('?') > -1)
serviceUrl += '&jsonp='
else
serviceUrl += '?jsonp='
serviceUrl += '?&type=1&StateId=';
serviceUrl += document.getElementById('<%= ddlState.ClientID%>').value;
$.ajax({
type: 'GET',
crossDomain: true,
async: false,
contentType: 'application/json; charset = utf-8',
url: serviceUrl,
data: '{}',
dataType: 'jsonp',
success: function (data) {
if (data != null && data.length > 0) {
$.map(data, function (item, index) {
var newListItem = document.createElement('option');
newListItem.text = item.City;
newListItem.value = item.CityId;
ddlcity.options.add(newListItem);
});
}
},
error: function (error) {
alert('error ' + error);
}
});
} // getCitydata()
To use this function you have to create one ashx file eg. Address.ashx file which consist method for getting the data from database

Submit form with jquery ajax

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

Categories

Resources