MVC5 Mqsql Issue - mysql

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
}
}

Related

Popup window in asp.net mvc

How to remove the menu part when the modal window pops up, and so that only the forms for inserting information remain. My code works fine. but when I press Edit button, it popups like the whole window with nav bar.
My Edit controller (Entity Framevork):
// GET: Products/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.FK_CATEGORY = new SelectList(db.Categories, "CATEGORY_ID", "CATEGORY_NAME", product.FK_CATEGORY);
return View(product);
}
// POST: Products/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PRODUCT_ID,PRODUCT_NAME,FK_CATEGORY")] Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FK_CATEGORY = new SelectList(db.Categories, "CATEGORY_ID", "CATEGORY_NAME", product.FK_CATEGORY);
return View(product);
}
My Edit PartialView:
#model MyNewApp5.Models.Product
<div class="modal-header">
<h4 class="modal-title">Edit product</h4>
</div>
<!-- Modal body -->
<div class="modal-body" id="editform">
<div class="form-horizontal">
#using (Html.BeginForm("Edit", "Products", FormMethod.Post, new { #id = "formsubmit" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PRODUCT_ID)
<div class="form-group">
#Html.LabelFor(model => model.PRODUCT_NAME, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PRODUCT_NAME, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PRODUCT_NAME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FK_CATEGORY, "FK_CATEGORY", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("FK_CATEGORY", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.FK_CATEGORY, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}
</div>
And my Index:
<div class="modal fade" id="myModal" role="dialog" data-url="#Url.Action("CreatePartialView", "Products")">
</div>
<script>
function editBut() {
$('.btn-success').click(function () {
var url = $('#myModalEdit').data('url');
$.get(url, function (data) {
$("#myModalEdit").html(data);
$("#myModalEdit").modal('show');
});
});
}
</script>
Edit |
try this
// Open modal in AJAX callback
$('btn-success').click(function(event) {
event.preventDefault();
this.blur(); // Manually remove focus from clicked link.
var url = $('#myModalEdit').data('url')
$.get(url, function(html) {
$(html).appendTo('body').modal();
});
});
<!-- AJAX response must be wrapped in the modal's root class. -->
<div class="modal">
</div>
it's taken from https://jquerymodal.com/ - Example 4: AJAX
I hope this helps

How to send nested json objects to the controller by using ajax

What I am trying to do is passing nested json objects to the controller
from where I have to set the field of those entity respectively. I have two entity named UserData and Address and I want to get nested objects for both the entity as the project requires.
As you can see at this phase I don't understand how to tackle this problem. help me out of this problem.
/front end/
<body>
<div class="container">
<div class="jumbotron">
<h1>File upload Demo</h1>
<p>File upload Demo along with the JSON data</p>
</div>
</div>
<div class="container">
<div class="alert alert-success">File uploaded successfully</div>
<div class="alert alert-danger">File is not uploaded. Error occurred</div>
<div class="form-group">
<label for="firstname">First Name:</label> <input type="text"
class="form-control" id="firstname" name="firstname">
</div>
<div class="form-group">
<label for="lastname">Last Name:</label> <input type="text"
class="form-control" id="lastname" name="lastname">
</div>
<div class="form-group">
<label for="state">State:</label> <input type="text"
class="form-control" id="state" name="state">
</div>
<div class="form-group">
<label for="city">City:</label> <input type="text"
class="form-control" id="city" name="city">
</div>
<form id="fileUploadForm">
<div class="form-group">
<input type="file" class="form-control-file border" name="file">
</div>
</form>
<button type="button" id="btnSubmit" class="btn btn-primary">Submit</button>
</div>
<script>
$(document).ready(function () {
$(".alert-success").hide();
$(".alert-danger").hide();
$("#btnSubmit").click(function () {
alert("hello");
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
var jsonDataObj = {
"firstname": $("#firstname").val(),
"lastname" : $("#lastname").val(),
"address" :{
"state": $("#state").val(),
"city" : $("#city").val()
}
};
data.append("jsondata", JSON.stringify(jsonDataObj));
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/upload",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
$(".alert-success").show();
$(".alert-danger").hide();
},
error: function (e) {
$(".alert-success").hide();
$(".alert-danger").show();
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
</script>
</body>
/**controller**/
#Controller
public class FileUploadRestController {
#Autowired UserRepo userRepo;
#Autowired uploadrep upld;
ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper addressmap = new ObjectMapper();
#RequestMapping(value="/upload", method=RequestMethod.POST)
public ResponseEntity<Object> uploadFile(#RequestParam(required=true, value="file") MultipartFile file, #RequestParam(required=true, value="jsondata")String jsondata) throws IOException, ParseException {
System.out.println("file name is "+file.getOriginalFilename());
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsondata);
//System.out.println(json.getString("firstname"));
/*File convertFile = new File("c://mydownloads//"+file.getOriginalFilename());
convertFile.createNewFile();
FileOutputStream fout = new FileOutputStream(convertFile);
fout.write(file.getBytes());
fout.close();*/
System.out.println("data ies "+json);
//UserData personData = objectMapper.readValue(jsondata, UserData.class);
//Address addressData = addressmap.readValue(jsondata, Address.class);
//Address address =new Address(addressData.getState(),addressData.getCity());
/*UserData userData=new UserData(StringUtils.cleanPath(file.getOriginalFilename()),file.getContentType(),file.getBytes(),personData.getFirstname(),personData.getLastname());
System.out.println("uploaded datafiles ");
//String str=Base64.getEncoder().encodeToString(file.getBytes());
userData.setAddress(address);
userRepo.save(userData);*/
return new ResponseEntity<>("File is uploaded successfully", HttpStatus.OK);
}

can't create new performance in mvc [duplicate]

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; }
}

How to Update data in Modal using Angular2?

This is My Angular2 part.Here Updateuser function for update data in database
export class UserprofileComponent
{
getdata : string;
public data;
Username : any ;
Firstname :any;
updateuser(){
let re = /[?&]([^=#&]+)=([^&#]*)/g;
let match;
let isMatch = true;
let matches = {};
while (isMatch)
{
match = re.exec(window.location.href);
if (match !== null)
{
matches[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
if (match.index === re.lastIndex)
{
re.lastIndex++;
}
}
else {
isMatch = false;
}
}
console.log(matches);
var headers= new Headers({'Content-Type' : 'application/x-www-form-urlencoded '});
var body = JSON.stringify({
username1 : this.user.Username,
firstname1 : this.user.Firstname,
})
this.http.post('../widgets/Update.php?ID='+matches['ID'],body, {
headers:headers; })
.map(res => res.json())
.map(res => {
if(res.success)
{
this.m=res.Message;
}
else{
this.m="wrong";
}
})
.subscribe(
data =>this.getdata = JSON.stringify(data),
err => console.error(err),
() => console.log('done'));
}
}
This is My html part:
<ngl-modal header=" Edit Profile" [(open)]="opened" [size]="size">
<div body>
<div class="form-horizontal" style="margin:auto;" id="editForm" *ngFor="#user of getdata">
<div class="form-group">
<label class="col-md-3 control-label">Username:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="cname" [(ngModel)]="user.Username" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Firstname:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="ads" [(ngModel)]="user.Firstname"/>
</div>
</div>
<span>{{m}}</span>
<button class="slds-button slds-button--neutral" (click)="cancel()">Cancel</button>
<button class="slds-button slds-button--neutral slds-button--brand" (click)="updateuser()">Save</button>
</ngl-modal>
Here I'd use modal for displaying the data which is display by ngFor.But I want to update this display data so how to do it?Because data is display by ngModel and when I'm taking the whole ngModel value for example if [(ngModel)]="user.name" then it showing the error that user is not define so what to do in this case??
My first guess would be trying let user of getdata instead of #user of getdata.
My second guess would be creating an Array of users getdata: Array<any> as a property of your class, instead of getdata:string, then assign to it.
My third guess: before you get the data, there are no users, so:
<div *ngIf='getdata' class="form-horizontal" style="margin:auto;" id="editForm" *ngFor="#user of getdata"> to make sure you don't try to access the object before it's there.
Before you call updateUser() there are no objects you could show, that's why users are undefined, as far as I can see.
Hope some of this helps, good luck.

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");
}
});