can't create new performance in mvc [duplicate] - html

I have this form:
#model CupCakeUI.Models.CupCakeEditViewModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createFrm" }))
{
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
<input type="text" id="Name" name="Name" value="#Model.Name" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model)
</div>
<div class="editor-field">
<input type="text" id="Price" name="Price" value="#Model.Price" />
</div>
<div class="col-md-offset-2 col-md-10">
<input type="button" id="btnCreate" value="Create" class="btn btn-default" />
</div>
</div>
}
I am trying to use ajax post to send data to the Action Method, however its always receiving empty object. I have done that several times in the past, and now i tried different ways which not working, The code:
$(document).ready(function () {
$("#btnCreate").click(function () {
var name = $("#Name").val();
var price = $("#Price").val();
var cupCakeEditModel = { "CupCakeId": 0, "Name": name, "Price": price };
var json = JSON.stringify(cupCakeEditModel);
$.ajax({
type: 'POST',
url: "/CupCake/Create",
data: JSON.stringify(cupCakeEditModel),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
})
})
Its showing this in the console when logging:
This is the Action Method and Class used:
[HttpPost]
public JsonResult Create (CupCakeUI.Models.CupCakeEditViewModel cupCakeEditModel)
{
var cupCake =
CupCakeData.Save(cupCakeEditModel);
return Json("cupCake",
JsonRequestBehavior.AllowGet);
}
This the class:
public class CupCakeEditViewModel
{
public int CupCakeId;
[Display(Name = "CupCake Name")]
public string Name;
public string Price;
}
I have also used this, but not working:
$("#btnCreate").click(function () {
var cupCakeEditModel =
$("#createFrm").serialize();
$.ajax({
url: "/CupCake/Create",
type: "POST",
data: cupCakeEditModel,
success: function (response) {
alert("Success");
},
error: function (response) {
}
});
})
And several answers i found on the forum, but it seems something weird!

You model contains only fields, and the DefaultModelBinder does not bind fields, only properties. Change the model to
public class CupCakeEditViewModel
{
public int CupCakeId { get; set; }
[Display(Name = "CupCake Name")]
public string Name { get; set; }
public string Price { get; set; }
}

Related

Display contents of SQL Table with Asp.Net Core MVC and FullCalendar

I have setup my app to display events on calendar. However, whilst the correct number of events will display the date and time is always the current date and time rather than what I have input into the SQL db table. Any help with what I am doing wrong would be greatly appreciated. My code is below:
View
#model IEnumerable<wccFacilityBookings.Models.Events>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="calender"></div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span id="eventTitle"></span></h4>
</div>
<div class="modal-body">
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print" />
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/applications/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay : v.IsFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD-
MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-
MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description:</b>' +
calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
}
})
}
})
</script>
}
Controller
// GET: Applications/CalendarView
public IActionResult CalendarView()
{
return View();
}
public JsonResult GetEvents()
{
using (WCCFacilityBookingsContext context = new WCCFacilityBookingsContext())
{
var events =_context.Events.ToList();
return Json(events);
}
}
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace wccFacilityBookings.Models
{
public class Events
{
[Key]
public int EventID { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string ThemeColor { get; set; }
public bool IsFullDay { get; set; }
}
}
Does this have something to do with it being Asp.Net Core?
Yes, in .NET Core 3.x, when you want to pass json from controller to client, it will camel-case all JSON output by default.
To avoid this, you can add the following setting in startup.cs ConfigureServices method:
services.AddMvc()
.AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
Since I added this setting before, the problem did not appear when I tested with your code. If I delete it, your problem will be reproduced.
So you have two solutions, change the field name to camel-case in js, or add the above code in startup.
OK, as always #YongquingYu got me on the right track. I am a 'nuffy' when it come to Ajax and Jquery. My issue, for reasons I don't understand was with capitalization, once I made the 'properties' lower case it worked. Does this have something to do with it being Asp.Net Core? Anyway my code (which is working as desired) is below:
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Applications/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.applicantContactName,
description: v.facility,
start: moment(v.start),
end: v.end != null ? moment(v.end) : null,
color: v.themeColor,
allDay: v.isFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start: </b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End: </b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description: </b>' +
calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
}
})
}
})
</script>
}
// GET: Applications/CalendarView
public IActionResult CalendarView()
{
return View();
}
public JsonResult GetEvents()
{
using (WCCFacilityBookingsContext context = new WCCFacilityBookingsContext())
{
var events = context.BookingApplications.ToList();
return Json(events);
}
}

pass a list of objects via ajax to a MVC controller always sends null

I am probably missing something very simple. I have been working on this for a day and an half now and can not get it to work. I am looping through a table and creating a list of objects to send back to my controller. For some reason I am always receiving a null value in my controller. Here is the java script.
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
url: './ReceivePOLines',
type: "Post",
cache: false,
data: JSON.stringify(items),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
here is the method signature in the controller
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions)
And here is the class ReceivedTransactions
public class RecievedTransactions{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
Here are the results from Fiddler showing what was passed
[{},{"numReceived":"10000","transactionID":"10661768"},{"numReceived":"10000","transactionID":"10661769"},{"numReceived":"2000","transactionID":"10661770"},{"numReceived":"2500","transactionID":"10661771"},{"numReceived":"2500","transactionID":"10661772"},{"numReceived":"2000","transactionID":"10661773"},{"numReceived":"10000","transactionID":"10661774"}]
Any and all help appreciated.
cheers
bob
This is a new answer. Originally, I was getting null, like you. But, now it works the way you want (array of complex objects). Please get this to work for you. If you can't get it to work, although it should, I can create an ASP.NET Fiddle.
public class RecievedTransactions
{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions) // MyArray MyArray
{
return;
}
//you use your own action name
public ActionResult Tut133()
{
return View();
}
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut132</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
//!!changing your url
//url: './ReceivePOLines',
url: "/Home/ReceivePOLines",
type: "Post",
cache: false,
//data: JSON.stringify({ MyArray: items }),
data: JSON.stringify(items),
//expecting back from server-need to remove since we are not getting back data from server
//dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
//alerting success instead of opening window
alert("success");
//window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
})
</script>
</head>
<body>
<table id="grid">
<tr>
<td><input type="text" id="NumReceived1" value="10000" /></td>
<td><input type="text" id="item_TransactionID1" value="10661768" /></td>
</tr>
<tr>
<td><input type="text" id="NumReceived2" value="10000" /></td>
<td><input type="text" id="item_TransactionID2" value="10661769" /></td>
</tr>
</table>
<input type="button" id="theButton" value="Go" />
</body>
</html>

AJAX AntiForgery Token not calling controller method

I am struggling to call my controller method with [ValidateAntiForgeryToken] attribute.
My cshtml/js code :
var wizardRegisterJsonRequest = {
Email: email,
Password: password,
ConfirmPassword: confirmPassword,
Name: name
};
$.ajax({
type: 'POST',
dataType: "html",
url: 'http://localhost:50209/GetAllFonts/WizardRegister',
data: AddAntiForgeryToken(wizardRegisterJsonRequest),
beforeSend: function () {
$('#create_account_form').data('busy', true);
$('#create_account_busy').show();
},
success: function (data) {
if (data.Success === true) {
// all good here
}
$('#create_account_validation_summary').text(data.Message);
$('#create_account_validation_summary').show();
},
complete: function () {
$('#create_account_form').data('busy', false);
$('#create_account_busy').hide();
}
});
AddAntiForgeryToken = function (data) {
alert("adding anti forgery");
data.__RequestVerificationToken = $('#anti_forgery_token').val();
return data;
};
Controller code :
[ValidateAntiForgeryToken]
[HttpPost]
public JsonResult WizardRegister(User usrDetails)
//public JsonResult WizardLogOn(User usr)
{
// string test = ""; // this method WizardRegister is not getting called
}
User model :
public class User
{
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string __RequestVerificationToken { get; set; }
}
I am not sure if I need __RequestVerificationToken in the User model. I am using AntiForgery for the first time.
Please let me know where I am going wrong ...
Thanks,
Rohan.
Update :
View / form code :
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "create_account_form" }))
{
#Html.AntiForgeryToken()
<fieldset>
<div class="input-fixed">
<span class="mandatory_wizard">* </span>
<input type="text" id="registrName" name="registrName" value="rohan" class="name" placeholder="Name">
</div>
<div class="input-fixed">
<span class="mandatory_wizard">* </span>
<input type="text" id="registrEmail" name="registrEmail" class="email" value="rohanskosht#gmail.com" placeholder="Email">
</div>
<div class="input-fixed">
<span class="mandatory_wizard"> </span>
<input type="text" class="phone" placeholder="Phone Number">
</div>
<div class="input-fixed">
<span class="mandatory_wizard">* </span>
<input type="password" id="registerPassword" name="registerPassword" value="12345678" class="password" placeholder="Password: Must be longer than 8 characters.">
</div>
<div class="input-fixed">
<span class="mandatory_wizard">* </span>
<input type="password" id="registerConfirmPassword" name="registerConfirmPassword" value="12345678" class="confirm-password" placeholder="Confirm Password">
</div>
<input type="submit" class="btn-modal-login" value="Create your account >>">
<img id="create_account_busy" style="display: none;" src="./Launch Campaign _ Teeyoot_files/busy.gif" alt="Loading...">
</fieldset>
}
#Html.AntiForgeryToken() generates a hidden input with name="__RequestVerificationToken". (it does not have an id attribute so $('#anti_forgery_token').val(); will return undefined.
You can access the value using
var token= $('[name=__RequestVerificationToken]').val();
However, I strongly suggest you generate the inputs for your properties using the HtmlHelper methods (#Html.TextBoxFor(m => m.Name), #Html.PasswordFor(m => m.Password) etc) rather than generating manual html and then you can simply use
data: $('form').serialize()
in the ajax call (and you can then delete most of your script). You should also not be hard coding the url (it will fail as soon as you put it into production). Your script simply needs to be
$.ajax({
type: 'POST',
dataType: "html",
url: '#Url.Action("WizardRegister", "GetAllFonts")',
data: $('form').serialize(),
beforeSend: function () {
....
You should also be including #Html.ValidationMessageFor() for each property to get client side validation so invalid forms are not submitted.
Side note: Its not clear from your code why you would use ajax. If the user is registering, then you would want to redirect if successful (and display validation errors if not), so ajax is pointless

MVC 5 - JSON post to controller always is null on controller side

I've looked for a couple hours now, hoping not to duplicate a question, and I just can't find what I'm looking for.
I am working on passing a complex object back from a form to a controller, and having it parse everything out. The problem I get is the controller shows a null input, despite the header post from Chrome showing the data going out. Can anyone give me a hand? I've included code below.
Model
public class QuizTakenObject
{
[NotMapped]
public QuizTakenComplete quizTakenComplete { get; set; }
[NotMapped]
public List<QuizSubmittedAnswers> submittedAnswers { get; set; }
[NotMapped]
public TopicList Topic { get; set; }
[NotMapped]
public QuizHeader QuizHeader { get; set; }
}
View/Script
#model App.Models.QuizTakenObject
#{
ViewBag.Title = "Take Quiz";
}
#section pageScripts{
<script type="text/javascript">
$(document).ready(function () {
//Highlight background of selected background for increased visibility
$("input[name^=QuizSubmittedAnswer]").change(function () {
$(this).parent().addClass("bg-primary");
$(this).parent().siblings().removeClass("bg-primary");
});
//Show save prompt on page after one answer is picked
var i = 0;
if (i == 0) {
$("input[name^=QuizSubmittedAnswer]").change(function () {
$("#quizSave").fadeIn('fast');
$("#quizSave").animate({ height: '125px' }, 'fast')
.animate({ width: '250px' }, 'fast', function () {
$("#quizSaveText").fadeIn('500');
});
});
}
//Prevent submitting before all answers have been selected
//Count all questions, one per form group
var questionsCount = $("form-group").length;
//Listen for answers to be selected
$("input[name^=QuizSubmittedAnswer]").change(function () {
//Check to see if all answers are selected
if ($("input[name^=QuizSubmittedAnswer]:checked").length >= questionsCount) {
$("#saveAndSubmitQuizButton").removeClass("disabled");
}
});
//Save and submit quiz
$("#saveAndSubmitQuizButton").click(function () {
event.preventDefault;
var complete = true;
saveQuizAttempt(complete);
});
//Save but not submit quiz
$("#saveQuizOnlyButton").click(function () {
event.preventDefault;
var complete = false;
saveQuizAttempt(complete);
});
//Create or update quiz attempt in DB
//saveQuizAttempt complete indicates if the record is to be marked as final
function saveQuizAttempt(complete) {
var array = $("#takeQuizForm").serializeArray();
//build JSON array
var json = {};
$.each(array, function () {
json[this.name] = this.value || '';
})
//array.push({ "IsComplete": complete });
//AJAX to post data
$.ajax({
type: "POST",
url: "SubmitQuiz",
data: JSON.stringify(array),
dataType: "json",
contentType:"application/json; charset=UTF-8",
success: function (data) {
console.log("Success!");
},
error: function () {
console.log("Error");
}
});
}
});
</script>
}
<style>
#quizSave {
display: none;
position: fixed;
z-index: 999;
height: 0;
width: 0;
bottom: 100px;
right: 0;
background-color: khaki;
border: 1px solid black;
border-radius: 2px 2px 2px 2px;
padding: .5em 1em .5em 1em;
}
</style>
<h2>#ViewBag.TopicName Quiz</h2>
<div class="row">
<div class="container col-xs-9 col-sm-9 col-md-9 col-lg-9">
<div class="well well-sm">
<strong>Directions:</strong> #Model.QuizHeader.QuizSummary
</div>
#using (Html.BeginForm("SubmitQuiz", "Quiz", FormMethod.Post, new { id = "takeQuizForm" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.QuizHeader.QuizID)
#Html.HiddenFor(model => model.QuizHeader.TopicID);
<input type="hidden" name="QuizTakenComplete.UserID" id="QuizTakenComplete.UserID" value="#(ViewBag.UserID)" />
<input type="hidden" name="QuizTakenComplete.IsComplete" id="QuizTakenComplete.IsComplete" value="false" />
<!--Questions/Answers-->
for (int i = 0; i < #Model.QuizHeader.QuizQuestions.Count(); i++)
{
<div class="quizQuestionBlock#(i)">
<hr />
<h4>#Model.QuizHeader.QuizQuestions.ElementAt(i).Question</h4>
<form-group>
<input type="hidden" name="QuizSubmittedAnswers[#(i)].QuestionID" id="QuizSubmittedAnswers[#(i)].QuestionID" value="#(Model.QuizHeader.QuizQuestions.ElementAt(i).QuestionID)">
#{for (int j = 0; j < Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.Count(); j++)
{
<!--answers via radio buttons-->
<div id="answer#(j)#(i)" class="quizAnswer#(j)">
<input type="radio" class="individualQuizAnswer" name="QuizSubmittedAnswers[#(i)].AnswerID" value="#Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.ElementAt(j).AnswerID"> #Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.ElementAt(j).Answer
</div>
}
}
</form-group>
</div>
}
<hr />
<button class="btn btn-success btn-block disabled" id="saveAndSubmitQuizButton" type="button">submit quiz</button>
<div style="text-align:center;">
<small> Submitting quiz will finalize this attempt and update your score records.</small>
</div>
<br />
<br />
}
</div>
<!--Sidebar-->
<div class="container col-xs-3 col-sm-3 col-md-3 col-lg-3">
<div class="panel panel-default">
<div class="panel-heading collapsable">
<h5><span class="glyphicon glyphicon-cog"></span> Actions</h5>
</div>
<div class="panel-body">
<span class="glyphicon glyphicon-backward"></span> #Html.ActionLink("return to library", "Index", new { controller = "Library" })<br />
#Html.ActionLink("cancel/go home", "Index", new { controller = "Home" }, new { #style = "color:red;" })
</div>
</div>
</div>
<!--Quiz Save/Quit-->
<div id="quizSave">
<div id="quizSaveText" style="display:none;">
Save current answers and return to App training/quiz library?<br />
<button type="button" id="saveQuizOnlyButton" class="btn btn-success">yes</button>
<button type="button" data-toggle="tooltip" class="btn btn-danger" title="this will cancel all previous work without saving and return to the main menu">no</button>
<br />
<small>You will be able to return later to resume your work.</small>
</div>
</div>
</div>
Controller
//POST: Quiz/SubmitQuiz
[HttpPost]
public async Task<ActionResult> SubmitQuiz(string quizObject)
{
//Send false value for complete in AJAX call, just parse based on this
//Two starting JS scripts, which flow into a unified function
var input = new JavaScriptSerializer().Deserialize<QuizTakenObject>(quizObject);
var quizTakenComplete = new QuizTakenComplete
{
UserID = input.quizTakenComplete.UserID,
IsComplete = input.quizTakenComplete.IsComplete,
LastUpdate = DateTime.Now
};
//Parse if complete for purposes of updating records.
if (quizTakenComplete.UserID != null || quizTakenComplete.UserID != "")
{
db.QuizTakenComplete.Add(quizTakenComplete);
await db.SaveChangesAsync();
var quizAttemptID = quizTakenComplete.QuizAttemptID;
//Now Add Each Answer
var quizTaken = new QuizSubmittedAnswers();
quizTaken.QuizAttemptID = quizAttemptID;
quizTaken.TopicID = input.Topic.TopicID;
quizTaken.QuizID = input.QuizHeader.QuizID;
return Content("Saved");
}
else
{
return Content("Not Saved");
}
}
I think that the problem is in Ajax Call you didn't specify the attribute name
try with this
$.ajax({
type: "POST",
url: "SubmitQuiz",
data: {quizObject : JSON.stringify(array)},
dataType: "json",
contentType:"application/json; charset=UTF-8",
success: function (data) {
console.log("Success!");
},
error: function () {
console.log("Error");
}
});

MVC5 Mqsql Issue

After Update of Model from database in Entity Framework. Json Data not populate into textbox. when i use DeveloperTool i found a error "There is already an open DataReader associated with this Connection which must be closed first."[Error 505] Help me for resolve this problem.am using MySql in my project. When i use only one table in Model then i didn't get any error but when i update model then my project not working. If i add all the tables in Model then I face same problem.
Here is my code
Controller:-
// GET: Chains
public ActionResult Index()
{
ViewData["chain_name"] = new SelectList(db.chains, "code", "name");
return View(db.chains.ToList());
}
//Action Function callby javascript
[HttpPost]
public ActionResult Action(string code)
{
var query = from c in db.chains
where c.code == code
select c;
return Json(query);//Return Json Result
}
View:-
#using (#Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<label class="col-sm-2 control-label">
Select Chain
</label>
<div class="col-md-3">
#Html.DropDownList("ddlchainname", (SelectList)ViewData["chain_name"], new { onchange = "Action(this.value);", #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
Chain Name
</label>
<div class="col-md-3">
#Html.TextBox("ChainName", null, new { #class = "form-control" })
</div>
<label class="col-sm-2 control-label">
Username
</label>
<div class="col-md-3">
#Html.TextBox("username", null, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
Chain Code
</label>
<div class="col-md-3">
#Html.TextBox("ChainCode", null, new { #class = "form-control" })
</div>
</div>
</div>
}
<script type="text/javascript">
function Action(code) {
$.ajax({
url: '#Url.Action("Action", "Chains")',
type: "POST",
data: { "code": code },
"success": function (data) {
if (data != null) {
var vdata = data;
$("#ChainName").val(vdata[0].name);
$("#ChainCode").val(vdata[0].code);
$("#username").val(vdata[0].username);
}
}
});
}
Try this approach:
using (var db = new ChainEntities())
{
ViewData["chain_name"] = new SelectList(db.chains, "code", "name");
return View(db.chains.ToList());
}
This way you open the connection only once then dispose when done.
Sane for action:
[HttpPost]
public ActionResult Action(string code)
{
using (var db = new ChainEntities())
{
var query = from c in db.chains
where c.code == code
select c;
return Json(query);//Return Json Result
}
}