Update single field using EF - entity-framework

I need to update a single field 'status' using EF..
View:
#model IEnumerable<DemoUserMeetings.Models.Meeting>
#{
ViewBag.Title = "Index";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table">
<tr>
<th>#Html.DisplayNameFor(m => m.MeetingFromId)</th>
<th>#Html.DisplayNameFor(m => m.MeetingToId)</th>
<th>#Html.DisplayNameFor(m => m.MeetingStartTime)</th>
<th>#Html.DisplayNameFor(m => m.MeetingEndTime)</th>
<th>#Html.DisplayNameFor(m => m.MeetingStatus)</th>
<th>#Html.DisplayNameFor(m => m.MeetingDescription)</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.MeetingFromId)</td>
<td>#Html.DisplayFor(modelItem => item.MeetingToId)</td>
<td>#Html.DisplayFor(modelItem => item.MeetingStartTime)</td>
<td>#Html.DisplayFor(modelItem => item.MeetingEndTime)</td>
<td>#Html.DisplayFor(modelItem => item.MeetingStatus)</td>
<td>#Html.DisplayFor(modelItem => item.MeetingDescription)</td>
<td>
<input type="button" class="btn btn-default btnAccept" value="Delete" id="#item.MeetingId" />
</td>
</tr>
}
Logout
<script type="text/javascript">
$('.btnAccept').click(function () {
var update_id = $(this).attr('id');
var isTrue = confirm("Accept meeting invite?");
if (isTrue) {
$.ajax({
url: '#Url.Action("AcceptMeeting","Home")',
type: 'POST',
data: { id: update_id },
success: function () {
alert('success');
},
error: function () {
alert('failed');
return false;
}
});
} else {
return false;
}
});
</script>
Controller:
[HttpPost]
public ActionResult AcceptMeeting(int id)
{
// Here i need to set status ="Accept" for particular id
return View();
}
that is what i tried, i want to update status of meeting having id to "Accepted". I know it is not a big thing but i am new to EF. i got the id of meeting in controller but dont know further process. any ideas?

try this
using (var db = new YourDBContext())
{
var meeting= context.Meeting.Find(id);
meeting.MeetingStatus = true;
db.Meeting.Attach(meeting);
db.SaveChanges();
}

Related

Error in filter function for VueJs

I want to filter the following in VueJs 2.
My Component is the following:
<template>
Search <input name="query" v-model="query" class="form-control">
<table class="table">
<thead>
<tr>
<th>User name</th>
<th>User email/th>
<th>Get logs</th>
</tr>
</thead>
<tbody v-for="user in filteredUsers">
<tr>
<td> {{ user.firstname }} </td>
<td> {{ user.lastname }} </td>
<td> <a v-on:click="getUserLogs(user.user_id)">Show</a> </td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import ConnectionService from '../../components/services/ConnectionService';
const connectionService = new ConnectionService();
export default {
data() {
return {
users: [],
query: '',
betweenDates: {
from: '',
to: ''
},
logs: {},
logsVisibility: false
}
},
created() {
this.getUsers();
},
computed: {
filteredUsers() {
return this.findBy(this.users, this.query, 'lastname')
}
},
methods: {
getUsers() {
this.$http.get(hostname + 'name=person_list&session_id=' + sessionApiId).then(response => {
this.users = connectionService.renderMultipleInstances(response.body);
}, response => {
// error callback
});
},
getUserLogs(id) {
let self = this;
axios.post('/logs/get_user_logs', {
userId: id,
}).then(function (response) {
self.logs = response.data;
self.logsVisibility = true;
console.log(response.data);
});
},
findBy(list, value, column) {
return list.filter(function (item) {
return item[column].includes(value)
})
}
}
}
</script>
I have the following data to filter through it:
users:Array[4095]
0:Object
firstname:"Анастасия"
id:206
lastname:"Никифорова"
middlename:"Юрьевна"
user_id:192
1:Object
firstname:null
id:3362
lastname:null
middlename:null
user_id:2046
...
And error is the following:
[Vue warn]: Error in render function: "TypeError: Cannot read property 'includes' of null"
In 1:Object lastname:null. It causes your error
You can add line before return
item[column] || (item[column] = '');
or
return list.filter(function (item) {
return (item[column] || '').includes(value)
})
I had a similar problem to fix it I replace every null value from my object with a ' ' (empty string)

Validation Message is not Displayed on View

This is not a repeated question am posting this question after trying all solutions.
I want to perform CRUD on a single View so I got this article
CRUD using SIngle View
It works fine but when I keep the text box empty then the Model is Valid returns false which is correct,after debugging it shows Name field is required but I cant see the error on the View.
Even #Html.ValidationSummary(true) is present in Begin Form
and #Html.ValidationMessageFor(model => model.Name)
So keeping the code short have used only one field
Model
public partial class tblClient
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
A class which handle multiple button
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
Controller
public class EmpController : Controller
{
SampleEntities1 db = new SampleEntities1();
//
// GET: /Emp/
public ActionResult Index(int? id)
{
ViewBag.Operation = id;
ViewBag.Name = db.tblClients.ToList();
tblClient objEmp = db.tblClients.Find(id);
return View(objEmp);
}
[HttpPost]
[HttpParamAction]
[ValidateAntiForgeryToken]
public ActionResult Create(tblClient objEmp)
{
if (ModelState.IsValid)
{
db.tblClients.Add(objEmp);
db.SaveChanges();
}
return RedirectToAction("Index");
}
[HttpPost]
[HttpParamAction]
[ValidateAntiForgeryToken]
public ActionResult Update(tblClient objEmp)
{
if (ModelState.IsValid)
{
db.Entry(objEmp).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index", new { id = 0 });
}
public ActionResult Delete(int id)
{
tblClient objEmp = db.tblClients.Find(id);
db.tblClients.Remove(objEmp);
db.SaveChanges();
return RedirectToAction("Index", new { id = 0 });
}
}
View
#using (Html.BeginForm())
{
<fieldset>
<legend><b>Emp Details</b></legend>
<table border="1" cellpadding="10">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
Action
</th>
</tr>
#foreach (var item in (IEnumerable<SingleVIewCrud.Models.tblClient>)ViewBag.Name)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.ActionLink("Edit", "Index", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
</fieldset>
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<fieldset>
<legend> <b>Entry Screen</b></legend>
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
<p>
<input type="submit" value="Create" name="Create"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:none" : "display:block") />
<input type="submit" value="Update" name="Update"
style=#((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />
</p>
</div>
</fieldset>
</div>
}
What is wrong that the validation error message is not displayed.
In both your Create() and Edit() POST methods, if ModelState is invalid, you just redirecting to the Index() view. You need to return the existing view -
if (!ModelState.IsValid()
{
return View(objEmp);
}
// save and redirect
db.tblClients.Add(objEmp);
db.SaveChanges();
return RedirectToAction("Index");
Side note: If you include the jquery.validate.js and jquery.validate.unobtrusive.js scripts, then you will also get client side validation and the POST methods will not even be hit - the validation messages will be displayed and the submit will be cancelled

Update partialview after Model updaton using Model popup

I have index page which contains 2 partial views.One for displaying Roles and another for displaying corresponding privileges.
#model IEnumerable<sample.Models.Role_Privilege_Map>
#{
ViewBag.Title = "RolePrivilgeMapping";
}
<h2>RolePrivilgeMapping</h2>
<script>
$(document).ready(function () {
registerTableClick();
//$("#tblRole tbody tr:first").trigger();
});
function registerTableClick() {
$("#tblRole tbody tr").on("click", function () {
$(this).siblings().removeClass('selected_row');
$(this).addClass("selected_row");
var roleId = parseInt($(this).find("td:eq(0)").text());
loadPrivilege(roleId);
});
function loadtrackPrivilege(roleId) {
$("#PrivilegeWrapper").load("#Url.Action("PrivilegesPartial", "RolePrivilegeMapping")",
{ 'roleID': roleId },
function (response, status, xhr) {
if (status == "error") {
alert("An error occurred while loading privileges.");
}
});
}
}
</script>
<div id="RolePrivilgeMappingWrapper">
<div class="float-left" id="roleWrapper">
#Html.Partial("_Role", sample.Models.DataProvider.DataProvider.GetRoleNames())
</div>
<div class="float-left" id="PrivilegeWrapper">
#Html.Partial("_Privilege", sample.Models.DataProvider.Provider.GetPrivilegeNames())
</div>
</div>
Here is my _Role.cshtml
#model IEnumerable<sample.Models.webpages_Roles>
#{
ViewBag.Title = "Index";
}
<script type="text/ecmascript">
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$(".editDialog").live("click", function (e) {
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Role',
autoOpen: false,
resizable: false,
height: 255,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
}
});
$("#dialog-edit").dialog('open');
return false;
});
});
</script>
<div class="settingsTable" style="position: relative; width: 100%; margin: 0 auto">
<div style="width: 50%; margin: 0 auto">
<div style="width: 50%; margin: 0 auto">
<h2>Role</h2>
</div>
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table id="tblRole">
<tr>
<th>
#Html.DisplayNameFor(model => model.RoleId)
</th>
<th>
#Html.DisplayNameFor(model => model.RoleName)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.RoleId)
</td>
<td>
#Html.DisplayFor(modelItem => item.RoleName)
</td>
<td>
#Html.ActionLink("Edit", "OpenEditRoleDialog", "RolePrivilegeMapping", new { id = item.RoleId }, new { #class="editDialog"}) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
<div id="dialog-edit" style="display: none">
</div>
</div>
On Role partial view I have edit link for every row displayed.
here is my _editrole.cshtml
#model sample.Models.webpages_Roles
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Ajax.BeginForm("EditRole", "RolePrivilegeMapping", new AjaxOptions { HttpMethod = "POST" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>webpages_Roles</legend>
#Html.HiddenFor(model => model.RoleId)
<div class="editor-label">
#Html.LabelFor(model => model.RoleName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RoleName)
#Html.ValidationMessageFor(model => model.RoleName)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Now while I click on edit link a jquery modal box gets displayed for editing details.I submit the changes asychronously as
#using (Ajax.BeginForm("EditRole", "RolePrivilegeMapping", new AjaxOptions { HttpMethod = "POST" }))
And the edit method is
public ActionResult EditRole(webpages_Roles webpages_roles)
{
if (ModelState.IsValid)
{
db.Entry(webpages_roles).State = EntityState.Modified;
db.SaveChanges();
}
return View("index");
}
My problem is
1. The dialog box is not getting closed. I have to manually click the cross
bar.
2. The Role partial view is not getting updated until I have to refresh the page.
I followed this link http://www.mindstick.com/Articles/279bc324-5be3-4156-a9e9-dd91c971d462/CRUD%20operation%20using%20Modal%20dialog%20in%20ASP%20NET%20MVC#.VVlyBLmqpHx

MVC binding list of object issue

Following my last post MVC model property null on posting form
and by looking in examples, I understand that when I need to post a
list from a view/partialView to the controller I should loop over the list and use
#HiddenFor property and on post, MVC can parse these fields into list.
Somehow the controller is not even been called, only when I remove these lines
#for (int i = 0; i < Model.To.Count; i++)
{
#Html.HiddenFor(m => m.To[i].UserName)
#Html.HiddenFor(m => m.To[i].FirstName)
#Html.HiddenFor(m => m.To[i].LastName)
}
the controller is being called but the sames problem occurs, my list is null.
My view:
#model Mobile.Models.MessageModel
<script type="text/javascript">
$(function () {
$('form').submit(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("message sent");
$('#messagedetails_panel').toggle();
$("#messages_panel").show();
$("#BtnSuccessMsg").click();
},
error: function (xhr, textStatus, errorThrown) {
alert("message failed");
}
});
}
return false;
});
});
</script>
<table id="messages_panel_mbar" cellpadding="0" cellspacing="0">
<tr>
<td class="left_mbar">
</td>
<td class="main_mbar">
</td>
<td id="back_msg_details" class="right_mbar"></td>
</tr>
</table>
<div style="height:10%; width:100%; font: bold; font-size: 20px; text-align:right;"> #Html.Raw(Model.Subject)</div>
<div id="msg_chat" style="text-align:right; width:100%; height:auto; max-height:80%; overflow-y:scroll;">
#Html.Raw(Model.MsgHistory)
</div>
<div id="reply_msg" style="height: 5%">reply</div>
<div id="reply_msg_block" class="visible" style="width:100%; height:45%;">
#using (Ajax.BeginForm("ReplyMessage", "SettingsMenu", null, new AjaxOptions { }, new { #class = "center_form" }))
{
#Html.ValidationSummary(true, "");
<br />
<fieldset style="height:75%">
#Html.HiddenFor(m => m.Subject)
#Html.HiddenFor(m => m.ParentId)
#Html.HiddenFor(m => m.From)
#Html.HiddenFor(m => m.fullnamesender)
#for (int i = 0; i < Model.To.Count; i++)
{
#Html.HiddenFor(m => m.To[i].UserName)
#Html.HiddenFor(m => m.To[i].FirstName)
#Html.HiddenFor(m => m.To[i].LastName)
}
<div id="textarea_msg_reply">
#Html.TextAreaFor(m => m.Content, new { #class = "" })
#Html.ValidationMessageFor(m => m.Content)
</div>
</fieldset>
<input type="submit" value="send" />
}
</div>
My Controller :
[HttpPost]
public ActionResult ReplyMessage(MessageModel model)// List<Contacts> is empty
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
try
{
model.Send();
}
catch
{
throw new HttpException(404, "Error");
}
}
throw new HttpException(404, "Error");
}
Please advice! Thanks!
Ok, so I figured it out.
I was doing every fine except that the Contact class didn't have a parameterless constructor.
my view:
#model Mobile.Models.MessageModel
<script type="text/javascript">
function showMessagesPanel1() {
$('#messagedetails_panel').toggle();
$("#messages_panel").show();
}
$('#back_msg_details').click(function () {
$.ajax({
url: '#Url.Action("Messages", "SettingsMenu")',
method: 'GET',
success: function (data) {
$("#messages_list").empty();
$("#messages_list").html(data);
$('#messagedetails_panel').toggle();
$("#messages_panel").show();
}
});
})
$('#reply_msg').click(function () {
if ($("#reply_msg_block").is(":visible")) {
$('#msg_chat').animate({ height: '80%' });
// $("#reply_msg_block").slideUp().removeClass('visible');
}
else {
$('#msg_chat').animate({ height: '35%' });
}
$("#reply_msg_block").animate({ heigh: 'toggle' }, 350);
})
$(function () {
$('form').submit(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("message sent");
$('#messagedetails_panel').toggle();
$("#messages_panel").show();
$("#BtnSuccessMsg").click();
},
error: function (xhr, textStatus, errorThrown) {
$('#reply_msg_block').html(xhr.responseText);
}
});
}
return false;
});
});
</script>
<table id="messages_panel_mbar" cellpadding="0" cellspacing="0">
<tr>
<td class="left_mbar">
</td>
<td class="main_mbar">
</td>
<td id="back_msg_details" class="right_mbar"></td>
</tr>
</table>
<div style="height:10%; width:100%; font: bold; font-size: 20px; text-align:right;"> #Html.Raw(Model.Subject)</div>
<div id="msg_chat" style="text-align:right; width:100%; height:auto; max-height:80%; overflow-y:scroll;">
#Html.Raw(Model.MsgHistory)
</div>
<div id="reply_msg" style="height: 5%">reply</div>
<div id="reply_msg_block" class="visible" style="width:100%; height:45%;">
#using (Ajax.BeginForm("ReplyMessage", "SettingsMenu", null, new AjaxOptions { }, new { #class = "center_form" }))
{
#Html.ValidationSummary(true, "");
<br />
<fieldset style="height:75%">
#Html.HiddenFor(m => m.Subject)
#Html.HiddenFor(m => m.ParentId)
#Html.HiddenFor(m => m.From)
#Html.HiddenFor(m => m.fullnamesender)
#for (int i=0; i<Model.To.Count; i++ )
{
#Html.HiddenFor(m => m.To[i].UserName)
#Html.HiddenFor(m => m.To[i].FirstName)
#Html.HiddenFor(m => m.To[i].LastName)
}
<div id="textarea_msg_reply">
#Html.TextAreaFor(m => m.Content, new { #class = "" })
#Html.ValidationMessageFor(m => m.Content)
</div>
</fieldset>
<input type="submit" value="send" />
}
</div>

mvc ajax begin form and renderpartial validation open

ı am using a view in ajax begin form. ı search one thing and result is correct then alert not render the partial view. but it isnt render correct view a blank page and a see my partial view. thanks
my view
#using (Ajax.BeginForm("AjazKullanici", new AjaxOptions { UpdateTargetId = "trBilgiler", HttpMethod = "Post" }))
{
<tr>
<td style="width: 20%">
T.C. Kimlik No :
</td>
<th align="left">
#Html.TextBoxFor(model => model.TcNo)
#Html.ValidationMessageFor(model => model.TcNo)
<input type="submit" id="btnBilgiGetir" value="Bilgi Getir" class="Button" width="75px" />
</th>
</tr>
}
<tr id="trBilgiler">
#{Html.RenderPartial("BilgilerKullanici");}
</tr>
my controller
public ActionResult AjazKullanici()
{
ViewData["dropGizliSoru"] = _db.EHASTANEGIZLISORUs;
return View();
}
[HttpPost]
public PartialViewResult AjazKullanici(YeniKullaniciModel model)
{
if (model.TcNo != null)
{
var userKontrol = _db.KULLANICIBILGILERIs.Where(x => x.KULLANICIKOD == model.TcNo);
if (userKontrol.Any())
{
Response.Write("<script langauge='javascript'>alert('Girmiş Olduğunuz T.C. Kimlik Numarasına Ait Kullanıcı Kaydı Vardır.')</script>");
return PartialView();
}
else
{
return PartialView("BilgilerKullanici",model);
}
}
return PartialView();
}