select dont save data on my database MVC/Json - json

I don't know why it don't save the AddressBookId form a select in my database
public class CreditCard
{
public int Id { get; set; }
[Display (Name="Customer")]
public int CustomerID { get; set; }
[Display(Name = "Billing Address")]
public int AddressBooKId { get; set; }
public virtual Customer Customer { get; set; }
}
Controller:
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "Id", "FullName");
ViewBag.CCTypeId = new SelectList(db.CreditCardTypes, "Id", "CCName");
return View();
}
public JsonResult AddList(int Id)
{
var add = from a in db.AddressBooks
where a.CustomerId== Id
select a;
return Json(new SelectList(add.ToArray(), "AddressBookId", "Address"), JsonRequestBehavior.AllowGet);
}
public IList<AddressBook> Getadd(int CustomeId)
{
return db.AddressBooks.Where(m => m.CustomerId== CustomeId).ToList();}
Mi view
<div class="form-group">
#Html.LabelFor(model => model.AddressBooKId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select><br />
#Html.ValidationMessageFor(model => model.AddressBooKId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
Json
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
$(function () {
$('#AddressBooKId').html(null)
$('#CustomerID').change(function () {
$.getJSON('/CreditCards/AddList/' + $('#CustomerID').val(), function (data) {
var items = '<option>Select a Address</option>';
$.each(data, function (i, add) {
items += "<option value='" + add.Value + "'>" + add.Text + "</option>"; });
$('#AddressBooKId').html(items);
}); }); });
</script>

Because your Dropdown is not bound with Model. You are creating it as independent control.
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select>
Change the list Id and name to "AddressBookList". Create hidden field to keep the AddressBookId using model.
#Html.HiddenFor(m => m.AddressBooKId);
Change your JS code to update the new dropdown name.
Create a new change event handler for AddressBookList and set the value of HiddenField.
$('#AddressBookList').change(function () {
$('#AddressBooKId').val($('#AddressBookList').val());
}
Now when form will be submitted the Model property AddressBookId will have the selected value.

Related

ASP.NET MVC not passing select list

I have the following form:
#using (Html.BeginForm())
{
#Html.LabelFor(a => a.SomeText)
#Html.TextBoxFor(a => a.SomeText, new { #class = "form-control" })
#Html.ValidationMessageFor(a => a.SomeText)
<select name="ListOne" id="ListOne">
#foreach (var item in Model.ListOne)
{
<option value="#item.Id">#item.Name</option>
}
</select>
#Html.DropDownListFor(a => a.ListTwo, listTwo, null);
<input type="submit" value="Do Stuff" class="btn-primary"
asp-controller="My" asp-action="DoStuff"/>
. . .
}
On the server side, I have a simple controller method:
public async Task<IActionResult> DoStuff(MyViewModel myViewModel)
{
// ...
}
A breakpoint here shows that neither select list gets passed through, despite them both being visible in the HTML.
The VM looks like this:
public class MyViewModel
{
public string? SomeText { get; set; }
public SelectList? ListOne { get; set; } = new(new List<SelectListItem>());
public SelectList? ListTwo { get; set; } = new(new List<SelectListItem>());
}
ListOne and ListTwo are both null.
Please - could someone tell me why?

razor select box cannot convert lambda expression

I need to convert this <select id="degreemultiselect" multiple="multiple"></select to a razor control #Html.DropDownList but I am getting the error message it says "cannot convert lambda expression to type string?" is that because of the model being a list public List<DegreeModel> selectedRequesterDegrees { get; set; } is there a work around for this?
#Html.DropDownList(x => x.selectedRequesterDegrees, new { id = "degreemultiselect", #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedRequesterDegrees)
Here is a working demo:
Model:
public class Test
{
public List<DegreeModel> selectedRequesterDegrees { get; set; }
}
View:
#model Test
#Html.DropDownListFor(x => x.selectedRequesterDegrees, new SelectList(Model.selectedRequesterDegrees, "Id", "Name"), null, new { id = "degreemultiselect", #class = "form-control" })
Controller:
[HttpGet]
public ActionResult Index()
{
var model = new Test()
{
selectedRequesterDegrees = new List<DegreeModel>()
{
new DegreeModel(){ Id=1,Name="aa"},
new DegreeModel(){ Id=2,Name="bb"},
new DegreeModel(){ Id=3,Name="cc"}
}
};
return View(model);
}
Result:

Input Tag Returns Null to The Model int the Create ActionResult

In The entity like this I put the HttpPostedFileBase with the name ImageFile us virtual because I'm using mapping
public class Slider : IEntity
{
public virtual int Id { get; set; }
public virtual HttpPostedFileBase ImageFile { get; set; }
}
Here in the entity im getting entity.ImageFile = null so below the actions code
[HttpPost]
public ActionResult AddOrEdit(Slider entity)
{
try
{
string fileName = Path.GetFileNameWithoutExtension(entity.ImageFile.FileName);
string extension = Path.GetExtension(entity.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
entity.Image = fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
entity.ImageFile.SaveAs(fileName);
if (ModelState.IsValid)
{
if (entity.Id == 0)
{
_sliderService.Insert(entity);
}
in the view i added the input tag with name ImageFile so normally I shouldn't get null ??
please help
#model Slider
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Slider", FormMethod.Post, new { id =
"form", enctype = "multipart/form-data" , onsubmit = "return
SubmitForm(this)" }))
{
#Html.HiddenFor(m => m.Id)
<div class="form-group" style="height:270px;">
#Html.LabelFor(m => m.ImageFile, new { #class = "blue-text", #style =
"font-size:16px", #id = "" })
<input name="ImageFile" type="file" />
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn" />
</div>
}
In order to get the file you can change the action params like this:
[HttpPost]
public ActionResult AddOrEdit(HttpPostedFileBase ImageFile,Slider slider)
{
....
}
but also you need to change your entity like this:
public class Slider : IEntity
{
public virtual int Id { get; set; }
public virtual string ImageUrl { get; set; }
}
then inside the action you can do:
if (ImageFile!= null)
{
slider.ImgUrl = SaveImage(ImageFile);
db.Slider.Add(slider);
db.SaveChanges();
}
and the SaveImage method:
private string SaveImage(HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
string relativePath = "~/Image/" + Path.GetFileName(uploadFile.FileName);
string physicalPath = Server.MapPath(relativePath);
uploadFile.SaveAs(physicalPath);
return uploadFile.FileName;
}
return null;
}
Thank you guys for your help , I solved it by removing" onsubmit = "return SubmitForm(this)" from the Html.BeginForm Tag , But in this case I'm not getting the Validation Messages or the notify messages any ideas ???
Below is the code of onsubmit
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
} else {
Popup.dialog('close');
$.notify(data.message, {
globalPosition: "top center",
className: "error"
})
}
}
});
}
return false;
}

MVC json save file

I got a view with some textbox and a submit button
when i push submit i want the data of the textboxes in a json file(no database)
Now it works only for save 1data command when i psuh a second time on submit with other data
then hen rewrite my json file how can i save all of it ?
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
// jsonkalender.Add(new kalender() { Password = "" });
//kalender kl = new kalender();
//kl.Password = obj.Password;
//kl.MyEnum = TestEnum.taak;
//obj.Password = kl.Password;
//Load(null);
return View();
}
private const string JsonFileName1 = #"C:\\Users\Alexander\Desktop\times1.json";
private List<kalender> _times;
[HttpPost]
public ActionResult Index(kalender obj)
{
// Load(obj);
// _times.Add(new kalender() { Datum = DateTime.Now.ToString() });
kalender kl = new kalender();
Json(new { datum = obj.Datum,wachtwoord = obj.Password });
// _times.Add(obj);
try
{
}
catch (Exception) { }
obj.SelectedEnumId++;
// kl.Password = obj.Password;
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
using (var writer = new StreamWriter(JsonFileName1))
{
writer.Write(json);
}
return View();
}
private void Load(kalender obj)
{
if (System.IO.File.Exists(JsonFileName1))
{
using (var reader = new StreamReader(JsonFileName1))
{
var json = reader.ReadToEnd();
obj = JsonConvert.DeserializeObject<kalender>(json);
}
}
if (obj == null)
obj = new kalender();
}
}
}
Model
public class kalender
{
//public string Datum { get; set; }
// [Required]
// [DataType(DataType.Date)]
// public Nullable<System.DateTime> Datum { get; set; }
public string Datum { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Type { get; set; }
[Required]
[Key]
public int SelectedEnumId { get; set; }
[Required]
public TestEnum MyEnum { get; set; }
}
}
View
#model PE1.Models.kalender
#{
ViewBag.Title = "Index";
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
}
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.Confirm = "Zeker?";
options.OnBegin = "OnBegin";
options.OnComplete = "OnComplete";
options.OnFailure = "OnFailure";
options.OnSuccess = "OnSuccess";
options.LoadingElementId = "divProgress";
options.LoadingElementDuration = 1000;
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
<script type="text/javascript">
$(function () { // will trigger when the document is ready
$('.datepicker').datepicker(); //Initialise any date pickers
});
</script>
<div>
<h1>Online Kalender</h1>
<div id="kader">
<p>THuis</p>
#using (Html.BeginForm("Index", "Home", options))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Kaldender</legend>
#*#Html.DropDownListFor(model => model.Password, listItems)*#<br />
#Html.LabelFor(model => model.Password)<br />
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)<br />
#Html.EnumDropDownListFor(model => model.MyEnum)
<div class="form-group input-group-sm">
#Html.LabelFor(model => model.Datum)
#Html.TextBoxFor(model => model.Datum, new { #class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
#Html.ValidationMessageFor(model => model.Datum)
</div>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</fieldset>
#Ajax.ActionLink("Klik hier om een Ajax ActionLink uit te voeren", "ProcessLink", options)
}
enum
public enum TestEnum : int
{
taak,
vergadering
}
my output is wrong how can i change it ?
{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}
this is my json file but i need this
[
{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
},{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}
]
Use the Overload for the SteamWriter object that appends to a file instead of overwriting a file.
http://msdn.microsoft.com/en-us/library/36b035cb(v=vs.110).aspx
using (var writer = new StreamWriter(JsonFileName1, true))
{
writer.Write(json);
}
Notice the addition of the bool true in the StreamWriter constructor

MVC4 Razor how to get selected value from dropdownlist?

My Model:
namespace mvc4deneme.Models
{
public class SiparisModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
[Display(Name = "Ürün Tipi")]
public Material UrunTipi { get; set; }
[Display(Name = "Yüzey")]
public Material Yuzey { get; set; }
public class Material
{
//public int? ID { get; set; }
public string ID { get; set; }
public string Name { get; set; }
}
}
MY CONTROLLER:
//my control page is SiparisController
public class SiparisController : Controller
{
//
// GET: /Siparis/
public ActionResult Index()
{
DataTable dt = null;
Material material = null;
var model = new SiparisModel();
List<Material> lstYuzey = new List<Material>{
new Material { ID = null, Name = "Seçiniz" },
new Material { ID = "D/-", Name = "Tek Yüz" },
new Material { ID = "D/D", Name = "Çift Yüz" } };
ViewBag.Yuzey = lstYuzey;
List<Material> lstUrunTipi = new List<Material> {
new Material { ID = null, Name = "Seçiniz" },
new Material { ID = "3100140", Name = "MKYL" },
new Material { ID = "3100180", Name = "FS.MKYL FA" },
new Material { ID = "3100190", Name = "FS.MKYL FC" },
new Material { ID = "3100090", Name = "YL" }, };
ViewBag.UrunTipi = lstUrunTipi;
return View(model);
}
}
MY Index.cshtml view page:
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedValue, Model.Values)
<button type="submit">OK</button>
#Html.LabelFor(m => m.UrunTipi)
#Html.DropDownListFor(m => m.UrunTipi.ID,
new SelectList(ViewBag.UrunTipi, "ID", "Name"),
new { style = "width:310px" })
#Html.ValidationMessageFor(m => m.UrunTipi.ID) }
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Yuzey)
#Html.DropDownListFor(m => m.Yuzey.ID,
new SelectList( ViewBag.Yuzey,"ID", "Name"),
new { style = "width:310px" })
#Html.ValidationMessageFor(m => m.Yuzey.ID)
}
My Ask:
How can i execute ok button to getting values of my UrunTipi and Yuzey selected values.
Thank you so much.
Regards,
B.Y.