我想在数据库中编辑这些数据并返回新数据
当我点击保存按钮时,数据不会改变
这是控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomPerformancePerformersModel customPerformancePerformersModel)
{
if (ModelState.IsValid)
{
int perfromanceId = Convert.ToInt32(TempData.Peek("CurrentPerformanceId"));
customPerformancePerformersModel.performanceObj = db.Performances.Where(x => x.PerformanceId == perfromanceId).FirstOrDefault();
db.Entry(customPerformancePerformersModel.performanceObj).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.EventId = new SelectList(db.Events, "EventId", "Name", customPerformancePerformersModel.performanceObj.EventId);
ViewBag.VenueId = new SelectList(db.Venues, "VenueId", "Name", customPerformancePerformersModel.performanceObj.VenueId);
ViewBag.Performers = new SelectList(db.PerformerPerformances, "Performers", "Name", customPerformancePerformersModel.performanceObj.PerformerPerformances);
return View(customPerformancePerformersModel.performanceObj);
}
这是html:
<div class="form-group">
@Html.LabelFor(model => model.performanceObj.IsVisible, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.performanceObj.IsVisible)
@Html.ValidationMessageFor(model => model.performanceObj.IsVisible, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.performanceObj.IsFeatured, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.performanceObj.IsFeatured)
@Html.ValidationMessageFor(model => model.performanceObj.IsFeatured, "", new { @class = "text-danger" })
</div>
</div>
答案 0 :(得分:1)
尝试以下方法:
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import os, json
import time
import configparser
# This is the Subscriber
settings = configparser.ConfigParser()
settings.read('VCAP_CONFIG.ini')
organization = settings['config']['org']
username = settings['config']['apikey']
password = settings['config']['authkey']
#Set the variables for connecting to the iot service
broker = ""
devicename = "007"
topic = "iot-2/type/DesktopApplication/id/007/evt/status/fmt/json"
#topic = 'iot-2/evt/status/fmt/json'
deviceType = "DesktopApplication"
clientID = "a:" + organization + ":appId"
print (clientID)
broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)
if username is not "":
mqttc.username_pw_set(username, password=password)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_message(mosq, obj, msg):
global message
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
def on_message(client, userdata, msg):
writeData = msg.payload.decode('utf-8')
parsed_json = json.loads(writeData)
UDD = parsed_json['UDD']
DDD = parsed_json['DDD']
PH = parsed_json['PH']
Ignition = parsed_json['Ignition']
# add the settings to the structure of the file, and lets write it out...
config = configparser.ConfigParser()
config['Data'] = {'UDD': UDD,
'DDD': DDD,
'PH': PH,
'Ignition':Ignition}
with open('Data.ini', 'w') as configfile:
config.write(configfile)
mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)
#print (test)
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message
mqttc.loop_forever()
答案 1 :(得分:0)
理想情况下,您的代码将如下所示:
public ActionResult Edit(int performanceId)
{
var model = db.Performances.FirstOrDefault(m => m.PerformanceId == performanceId);
return View(model);
}
[HttpPost] //[HttpPatch] is technically correct, but most people I see tend to use only GET and POST actions.
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomPerformancePerformersModel model)
{
if (ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
}
}
您正在从数据库中检索对象并在GET
操作中对其进行跟踪,使用您的表单对其进行修改,然后在更新操作中将其标记为已修改。如果您正在使用MVC模式,这是严格的,如果您使用单独的数据和视图模型,则会看起来不同(见下文)。如果您的视图没有模型中所有属性的字段(隐藏或不隐藏),您可能会遇到此方法的问题。
使用单独的数据和视图模型,您将拥有以下内容:
public ActionResult Edit(int performanceId)
{
var performance = db.Performances.FirstOrDefault(m => m.PerformanceId == performanceId);
var model = new PerformanceViewModel(performance); //In this constructor, copy properties from your data model to your view model
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PerformanceViewModel model)
{
var performance = db.Performances.FirstOrDefault(m => m.PerformanceId == model.PerformanceId);
model.Update(performance);
db.SaveChanges();
}
使用示例视图模型:
public class PerformanceViewModel
{
public PerformanceViewModel(CustomPerformanceePerformersModel model)
{
PerformanceId = model.performanceObj.PerformanceId;
IsVisible = model.performanceObj.IsVisible;
IsFeatured = model.performanceObj.IsFeatured;
}
public int PerformanceId { get; set; }
public bool IsVisible { get; set; }
public bool IsFeatured { get; set; }
public void Update(CustomPerformancePerformersModel model)
{
model.performanceObj.IsVisible = IsVisible;
model.performanceObj.IsFeatured = IsFeatured;
}
}
在这里,您要创建一个单独的对象(视图模型),该对象仅包含视图所需的数据,然后使用该对象中的数据更新数据模型。我更喜欢这个,因为它能够有效地直接修改数据库,并且因为你可以在Update(Model)方法中进行任何必要的中间处理(将字符串转换为bool等)。