I am working on the MVC3 with ADO.Net Connectivity, an then i am updating the div with jQuery
Here i my code
Controller
public ActionResult GetData()
{
return this.Json(_db.MYMOVIELISTs, JsonRequestBehavior.AllowGet);
}
public void Insert(string Id)
{
var movieToInsert = new MYMOVIELIST { Title = "Ben", Director = "LEMe", ID = Id };
// Save new movie to DB
_db.AddToMYMOVIELISTs(movieToInsert);
_db.SaveChanges();
}
ClientSide
function insertCallback(result) {
readData();
}
function readData() {
info.empty();
$.ajax({
type: "GET",
url: 'Home/GetData',
async: false,
success: function (data) {
for (var i = 0; i < data.length; i++) {
var panel = $("<div class='panel' ></div>")
var d = data[i];
panel.append("ID: " + d.ID + "</br>");
panel.append("Title: " + d.Title + "</br>");
panel.append("Director: " + d.Director + "</br>");
panel.append("<hr>");
panel.data("info", d);
panel.appendTo(info);
}
}
});
}
$("#btnAdd").click(function () {
$.post("Home/Insert", $("form").serialize(), insertCallback);
});
This is works Fine, my problem is i want to update the Database table in "Save" buttom click. i tried to call the _db.SaveChanges(); in save button click instead of the Insert it is not adding the movieToInsert to table, here i want to know is how to save the database later, Here any thing am doing wrong or is there any best approach for DB connectivity
You are serializing a form, so eventually you may want below... which will bind your serialized form to the a movie model/entity:
[AcceptVerbs("POST")]
public void Insert(MovieEntity movie)
As for database practice, I recommend reading about the repository pattern and dependency injection as it pertains to ASP.NET MVC.
Related
I have an asp.net mvc project. I am getting some questions and answers for questions from database by ajax get. My query takes too long. How can i edit my code to work faster?
I am storing my questions and answers seperate tables. Each answer is related questions by ids.
Thanks for answers.
My view:
$.ajax({//GET QUESTIONS
url: '#Url.Action("GetQuestionsBySubCategory", "Order")',
type: "GET",
data: { subcattext : selectedSubCategory },
success: function (result) {
$('<div class=\"form-group\" id=\"sorularform\" ><input name=\"altcat\" value=\"' + selectedSubCategory + '\" type=\"hidden\">').prependTo("#sorular");
// loop each question
for (var i = 0; i < result.length; i++) {
//IF QUESTION 1 START
if (result[i].QuestionType == 1) {
$('<label for=\"exampleFormControlSelect' + i + '\" > ' + result[i].Description + '</label ><select name=\"' + result[i].Description + ' \" class=\"form-control\" id=\"exampleFormControlSelect' + result[i].Id + '\"></select>').appendTo("#sorularform");
var questionid;
$.ajax({//GET ANSWERS
url: '#Url.Action("GetAnswersByQuestionId", "Order")',
type: "GET",
data: { questionid: result[i].Id },
success: function (answerresult) {
for (var a = 0; a < answerresult.length; a++) {
$('<option>' + answerresult[a].Description + '</option>').prependTo("#exampleFormControlSelect" + answerresult[a].Question_Id);
}
},
error: function (err) {
// the call thrown an error
console.log("Hata Oluştu")
},
complete: function () {
//$(".loading").hide();
}
});
};
}
},
error: function (err) {
// the call thrown an error
console.log("Hata Oluştu")
},
complete: function () {
//$(".loading").hide();
$("</div>").appendTo(".form-group");
$('#yersec').insertBefore('#sorularform');
//$('#sorular').html(table);
}
});
Controller.cs
public ActionResult GetQuestionsBySubCategory(string subcattext)
{
var subcatid = subCategoryServices.GetAll().Where(x => x.Title == subcattext).FirstOrDefault().Id;
IEnumerable<QuestionVM> questionList = questionServices.GetAll().Where(x => x.SubCategory_Id == subcatid);
return Json(questionList, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult GetAnswersByQuestionId(int questionid)
{
IEnumerable<AnswerVM> answerList = answerServices.GetAll().Where(x => x.Question_Id == questionid);
return Json(answerList, JsonRequestBehavior.AllowGet);
}
If you want to make your querying faster, I would recommend Dapper. Dapper is a lightweight ORM that runs almost as fast as native SQL. There is a good tutorial that I would recommend you reading here: https://www.c-sharpcorner.com/article/asp-net-mvc-crud-with-dapper-micro-orm/
Essentially, you'll be running queries like this (this isn't exact but it's very close to the Dapper syntax without seeing your database structure or the rest of your code):
public ActionResult GetQuestionsBySubCategory(string subcattext)
{
var subcatid = db.Query("SELECT Id from SubcategoryServices WHERE Title = #title", new { title = subcattext });
IEnumerable<QuestionVM> questionList = db.Query("SELECT * FROM QuestionServices WHERE SubCategory_Id = #subcategoryId", new { subcategoryId = subcatid });
return Json(questionList, JsonRequestBehavior.AllowGet);
}
Aside - your DOM manipulation is very slow too, so that could also be making your application slower too. The technical reason is because the DOM has to re-render itself once you append elements to it. Rendering takes time.
It is out of the scope to create your whole application here, but I would strongly recommend at ReactJs or Vue as front-end libraries to create faster frontend code.
I am beginner and trying to update my record by using Ajax call in Entity Framework MVC. I am getting idtoSearch successfully but not getting std.FirstName and std.LastName at controller side. As you can see in my code here
AjaxStudentController
[HttpPost]
public ActionResult UpdateStudent(Student std, int idtoSearch) {
using (StudentContext db = new StudentContext()) {
Student updatestd = db.Student.Find(idtoSearch);
if (!string.IsNullOrWhiteSpace(std.FirstName)) { updatestd.FirstName = std.FirstName; }
if (!string.IsNullOrWhiteSpace(std.LastName)) { updatestd.LastName = std.LastName; }
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
and here you can see ajax code
<button class='upbtn' data-upid=" + stdid + ">Update</button>
$(".upbtn").click(function () {
var student = {
"upFirstName" : $("#name").val(),
"upLastName" : $("#lname").val(),
}
$.ajax({
url: "/AjaxStudent/UpdateStudent",
method: "Post",
data: {
idtoSearch: upid,
std: student
}
}).done(function(){
alert("Update button");
}).
error(function () {
alert("Update Error");
});
});
I am unable to get any update at browser. Anybody please tell me what should I do.
I have solved my problem. I was updating my data in wrong variable i.e. upFirstName & upLastName. That was my mistake. I should update my data in same variable i.e. FirstName & LastName. Just write below code
var student = {
"FirstName" : $("#name").val(),
"LastName" : $("#lname").val(),
}
Instead of this
var student = {
"upFirstName" : $("#name").val(),
"upLastName" : $("#lname").val(),
}
I hope it's will be helpful for you also.
I have a simple page with an input text-box. The text box is bound to jquery ui autocomplete that makes an AJAX call to the server. My server side code is an ASP.NET MVC site. The only difference I have as compared to most examples found over the Internet is that my Server side code returns a PartialView (html code) as results instead of JSON. I see the AJAX call happening and I see the HTML response in the AJAX success event as well.
My question is how do I bind this HTML data to show in the AutoComplete?
The code I have so far is:
$("#quick_search_text").autocomplete({
minLength: 3,
html: true,
autoFocus: true,
source: function (request, response) {
$.ajax({
type: "POST",
url: "serversideurl",
data: "{ 'SearchTerm': '" + request.term + "', 'SearchCategory': '" + $("#quick_search_category").val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
},
success: function (data) {
//THIS IS WHERE MY HTML IS RETURNED FROM SERVER SIDE
//HOW DO I BIND THIS TO JQUERY UI AUTOCOMPLETE
}
});
},
select: function (event, ui) {
},
response: function (event, ui) {
console.log(ui);
console.log(event);
}
});
This works:
1) Create an action in your controller and set the RouteConfig to start this action
public class HomeController : Controller
{
public ActionResult Index20()
{
MyViewModel m = new MyViewModel();
return View(m);
}
Create a view without any type of master page
Add this view model:
public class MyViewModel
{
public string SourceCaseNumber { get; set; }
}
Go to Manage Nuget Packages or PM Console and add to MVC 5 project - Typeahead.js for MVC 5 Models by Tim Wilson
Change the namespace for the added HtmlHelpers.cs to System.Web.Mvc.Html and rebuild
Add this class:
public class CasesNorm
{
public string SCN { get; set; }
}
Add these methods to your controller:
private List<Autocomplete> _AutocompleteSourceCaseNumber(string query)
{
List<Autocomplete> sourceCaseNumbers = new List<Autocomplete>();
try
{
//You will goto your Database for CasesNorm, but if will doit shorthand here
//var results = db.CasesNorms.Where(p => p.SourceCaseNumber.Contains(query)).
// GroupBy(item => new { SCN = item.SourceCaseNumber }).
// Select(group => new { SCN = group.Key.SCN }).
// OrderBy(item => item.SCN).
// Take(10).ToList(); //take 10 is important
CasesNorm c1 = new CasesNorm { SCN = "11111111"};
CasesNorm c2 = new CasesNorm { SCN = "22222222"};
IList<CasesNorm> aList = new List<CasesNorm>();
aList.Add(c1);
aList.Add(c2);
var results = aList;
foreach (var r in results)
{
// create objects
Autocomplete sourceCaseNumber = new Autocomplete();
sourceCaseNumber.Name = string.Format("{0}", r.SCN);
sourceCaseNumber.Id = Int32.Parse(r.SCN);
sourceCaseNumbers.Add(sourceCaseNumber);
}
}
catch (EntityCommandExecutionException eceex)
{
if (eceex.InnerException != null)
{
throw eceex.InnerException;
}
throw;
}
catch
{
throw;
}
return sourceCaseNumbers;
}
public ActionResult AutocompleteSourceCaseNumber(string query)
{
return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
}
credit goes to http://timdwilson.github.io/typeahead-mvc-model/
am using asp.net mvc3, i have 2 tables in that i want to get data from dropdown based on this another dropdown has to perform.for example if i select country it has to show states belonging to that country,am using the following code in the controller.
ViewBag.country= new SelectList(db.country, "ID", "Name", "--Select--");
ViewBag.state= new SelectList("", "stateID", "Name");
#Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewBag.country, "-Select-")
#Html.DropDownListFor(model => model.state, (IEnumerable<SelectListItem>)ViewBag.state, "-Select-")
but by using this am able to get only the countries.
There is a good jQuery plugin that can help with this...
You don't want to refresh the whole page everytime someone changes the country drop down - an ajax call to simply update the state drop down is far more user-friendly.
Jquery Ajax is the best Option for these kind of questions.
Script Code Is Given below
<script type="text/javascript">
$(function() {
$("##Html.FieldIdFor(model => model.Country)").change(function() {
var selectedItem = $(this).val();
var ddlStates = $("##Html.FieldIdFor(model => model.state)");
$.ajax({
cache:false,
type: "GET",
url: "#(Url.Action("GetStatesByCountryId", "Country"))",
data: "countryId=" ,
success: function (data) {
ddlStates.html('');
$.each(data, function(id, option) {
ddlStates.append($('<option></option>').val(option.id).html(option.name));//Append all states to state dropdown through returned result
});
statesProgress.hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to retrieve states.');
statesProgress.hide();
}
});
});
});
</script>
Controller:
public ActionResult GetStatesByCountryId(string countryId)
{
// This action method gets called via an ajax request
if (String.IsNullOrEmpty(countryId))
throw new ArgumentNullException("countryId");
var country = GetCountryById(Convert.ToInt32(countryId));
var states = country != null ? GetStatesByConutryId(country.Id).ToList() : new List<StateProvince>();//Get all states by countryid
var result = (from s in states
select new { id = s.Id, name = s.Name }).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Try this,
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var Id = $("#Country").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { Country: Id },
success: function (listItems) {
var STSelectBox = jQuery('#state');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
View
#Html.DropDownList("Country", (SelectList)ViewBag.country, "--Select--")
#Html.DropDownList("state", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Controller
public JsonResult GetCustomerNameWithId(string Country)
{
int _Country = 0;
int.TryParse(Country, out _Country);
var listItems = GetCustomerNameId(_Country).Select(s => new SelectListItem { Value = s.CountryID.ToString(), Text = s.CountryName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}
Hi all i have ajax where i have some data And a controller action method ...i need to send the data to the controller action method ...when i am doing this it has null values in my controller method ,can any one correct me where am i doing worng...
<script type="text/javascript">
$(document).ready(function () {
$("#butValidateForm").click(function () {
UpdateMethod();
})
});
function UpdateMethod() {
var s = document.getElementById("EmployeeID");
var selecteditem1 = s.options[s.selectedIndex].value;
var a = document.getElementById("FromStatusId");
var selecteditem6 = a.options[a.selectedIndex].value;
var data = '{"AssignTo":"' + selecteditem1 + '","Status":"' + selecteditem6 + '"}';
alert(data);
$.ajax({
type: "POST",
url: "/ViewBug/Update/",
enctype: 'multipart/form-data',
data: data,
success: function () {
}
});
}
</script>
my contoller action method
[HttpPost]
public ActionResult Update(BugModel model, FormCollection form, string selecteditem1, string selecteditem6)
{
if (Session["CaptureData"] == null)
{
}
else
{
model = (BugModel)Session["CaptureData"];
}
ViewBag.AssignTo = new SelectList(GetEmployee(), "EmployeeID", "EmployeeName");
ViewBag.Status = new SelectList(GetFromStatus(), "FromStatusId", "FromStatus");
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("sp_history", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.Parameters.Add("#Title", SqlDbType.VarChar).Value = model.Title;
cmd.Parameters.Add("#FixedById", SqlDbType.VarChar).Value = model.LoginName;
cmd.Parameters.Add("#AssignedId", SqlDbType.Int).Value = model.AssignTo;
cmd.Parameters.Add("#Resolution", SqlDbType.VarChar).Value = model.Resolution;
cmd.Parameters.Add("#FromStatus", SqlDbType.VarChar).Value =model.Status;
string fileName = string.Empty;
string StrFilePath = string.Empty;
foreach (BugAttachment objList in model.ListFile)
{
if (string.IsNullOrEmpty(StrFilePath))
{
fileName = objList.AttachmentName;
StrFilePath = objList.AttachmentUrl;
}
else
{
fileName = fileName + "," + objList.AttachmentName;
StrFilePath = StrFilePath + "," + objList.AttachmentUrl;
}
}
cmd.Parameters.Add("#AttachmentName", SqlDbType.VarChar).Value = fileName;
cmd.Parameters.Add("#BugAttachmentUrl", SqlDbType.VarChar).Value = StrFilePath;
cmd.Parameters.Add("#AttachedBy", SqlDbType.VarChar).Value = model.LoginName;
cmd.ExecuteNonQuery();
conn.Close();
}
return View("Edit");
}
Instead of
public ActionResult Update(BugModel model, FormCollection form, string selecteditem1, string selecteditem6)
give this a try:
public ActionResult Update(BugModel model, FormCollection form, string AssignTo, string Status)
You need to use the names of the property you have used in the object your sending back as you have named them AssignTo and Status. Hope this helps.
Edit:
Try sending the object like this:
var data ={};
data.AssignTo = selectedvalue1;
data.Status = selectedvalue6;
See if that makes any difference. If your still having issues can you inspect the request in firebug/developer tools?
Try this:
var data = { AssignTo: selecteditem1, Status: selecteditem6 };
also, as per Henry's answer, use the signature:
public ActionResult Update(BugModel model,
FormCollection form,
string AssignTo,
string Status)
tho, you should of course be able to get both the required values from the form[] collection, given that you are doing an HttpPost behind the scenes:
(i.e. var assignTo = form["AssignTo"]; etc).
[Edit] - out of curiousity, can I ask why you mix and match jquery syntax with more traditional javascript object syntax. one example being where you get the value of the EmployeeID option?? why not just use var selecteditem1 = $('#EmployeeID').val();.
I also notice the ViewBag object getting updated in your HttpPost action. Are you expecting to be able to use that on returning to the view -surely not (not in terms of the ajax request anyway). A quick explanation for my curiousity would be great. In my opinion, you are trying to do too much with this action (sure, keep it DRY - but) and I'm fearful that you'll end up getting into a corner with the number of different entry points you appear to be building up. I'd suggest a gentle rewind, just to keep things a little more focussed and each action having a single responsibility.
I ended up doing the following:
<script type="text/javascript">
$(document).ready(function () {
$("#butValidateForm").click(function () {
UpdateMethod();
})
});
function UpdateMethod() {
var s = document.getElementById("EmployeeID");
var selecteditem1 = s.options[s.selectedIndex].value;
var a = document.getElementById("FromStatusId");
var selecteditem6 = a.options[a.selectedIndex].value;
// var data = '{AssignTo:' + selecteditem1 + '}';
// alert(data);
var AssignTo;
var Title;
Title=$("#Title").val();
var FixedBy;
FixedBy = $("#LoginName").val();
var Resolution;
Resolution = $("#Resolution").val();
var Status;
Status = $("#FromStatusId").val();
$.ajax({
type: "POST",
url: "/ViewBug/Update/",
enctype: 'multipart/form-data',
data: {AssignTo:selecteditem1,Title:Title,FixedBy:FixedBy,Resolution:Resolution,Status:Status},
success: function () {
}
});
}
</script>