I want to use create, but when I post my values don´t register in my database also in my view too.
Model:
public class WebPages
{
[Key]
public DateTime DomainStart { get; set; }
public DateTime DomainExp { get; set; }
}
ViewModel:
public class WebPagesViewModel
{
public DateTime DomainStart { get; set; }
public DateTime DomainExp { get; set; }
}
Post Controller:
[HttpPost]
public async Task<ActionResult>Create([Bind(Include = "DomainName,DomainExp")] WebPagesViewModel model)
{
if (ModelState.IsValid)
{
model.WC();
await db.SaveChangesAsync();
return RedirectToAction("Index", "WebPages");
}
return View(model);
}
Extension method of my post:
public static WebPagesViewModel WC(this WebPagesViewModel model)
{
var wb= new WebPages
{
DomainStart = model.DomainStart,
DomainExp = model.DomainExp,
};
db.WebPagesList.Add(wb);
db.SaveChangesAsync();
return model;
}
So try catch pass, and I get a success post, but values don´t save on database, what I´m doing wrong?
Thankyou in advance!
[HttpPost]
public async Task<ActionResult>. Create([Bind(Include = "DomainName,DomainExp,DomainEmails,DomainUsers,DomainPasswords,ClientsName")]
Change your post method to
[HttpPost]
public async Task<ActionResult> Create([Bind(Include = "DomainName,DomainExp,DomainEmails,DomainUsers,DomainPasswords,ClientsName")]
//model.WebPagesCreate();
pass parameter to the above method
if you want to see error
db.SaveChangesAsync()
change to
db.SaveChanges()
And also check bind values are correctly coming from the view
Add this to view model
public WebPagesViewModel()
{
AvalilableClients = new List<SelectListItem>();
}
public List<SelectListItem> AvalilableClients { get; set; }
Add your client list to Model
foreach (var client in Clients )
{
model.WebPagesViewModel.Clients .Add(item: new SelectListItem()
{
Text = dept.DepartmentName,
Value = dept.DepartmentId.ToString()
});
}
Then Pass model to View Then populate the view drop down using Html Healper
#Html.DropDownListFor(model => model.SelectedClient, Model.AvalilableClients , new { #class = "form-control" })
Finally I solve it, the problem was that my datetime is not setted correctly in my extension method, so I change DomainStart = model.DomainStart to DomainStart = Datetime.now
Related
I have a model DropDownConfiguration which is fetching values from database and populating the dropdown list.
Model:
public class DropDownConfiguration
{
public int ID { get; set; }
public int Quarter { get; set; }
public int Year { get; set; }
public string Project { get; set; }
public string LineID { get; set; }
}
html:
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "ID", "Project"), "-- Select Project --", new { required = true, #class = "form-control" })
I have another model DetailsConfiguration which has all the fields which need be saved into the database.
public class DetailsConfiguration
{
public int Quarter { get; set; }
public int Year { get; set; }
public string Project { get; set; }
public string ItemModel { get; set; }
}
Controller HttpPost:
[ActionName("DetailsForm")]
[HttpPost]
public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
{
DetailsConfiguration detailsConfig = new DetailsConfiguration();
detailsConfig.Quarter = Convert.ToInt32(form["Quarter"]);
detailsConfig.Year = Convert.ToInt32(form["Year"]);
detailsConfig.Project = model.detailsConfig.Project;
detailsConfig.ItemModel = model.detailsConfig.ItemModel;
detailsConfig.LineID = model.detailsConfig.LineID;
floorService.SaveDetails(detailsConfig);
ModelState.Clear();
ViewBag.message = "Success";
return View("DetailsForm");
}
Is there anyway to do something like:
model.detailsConfig.Project = model.dropConfig.Project
I need the selection of Project to be posted back to database through DetailsConfiguration.
You could create a mapper which sets the values of the properties in DropDownConfiguration to DetailsConfiguration.
When you change the dropdown you send the selected DropDownConfiguration to the server. You know exactly what properties you can expect here so you can do something like this:
[HttpPost]
public IHttpActionResult AddDetailsConfiguration(DropDownConfiguration parameter)
{
//check here if values in parameter are set
var detailsConfiguration = new DetailsConfiguration {
Quarter = parameter.Quarter,
Year = parameter.Year,
Project = parameter.Project
}
//Insert detailsConfiguration to database
Return Ok();
}
Note that you have to make sure you send a DropDownConfiguration object on selecting a dropdown item. You could also only send the values you need like this:
[HttpPost]
public IHttpActionResult AddDetailsConfiguration(int quarter, int year, string project)
{
//Check here if values in parameter are set and if values are correct
var detailsConfiguration = new DetailsConfiguration
{
Quarter = quarter,
Year = year,
Project = project
}
//Insert detailsConfiguration to database
Return Ok();
}
I started working with asp.net and I have encountered a problem when I try to edit multiple values from a table. I have a bookmark tables which is connected to another tag table, with an 1 : N relationship. My problem is when I want to edit already existing tags associated with an existing url. I can display them on the page but when I try to post the edited data I don't know how to pick it up in the controller. So far I have managed to send them back as a string but I doubt that is the solution since I have to edit all the data again later. I want to replace the existing values in the Tag table with the edited data. Here are my model and controller code snippets.
Bookmark model:
public int id { get; set; }
public string url { get; set; }
public virtual ICollection<Tag> tags { get; set; }
Tag model:
public int id { get; set; }
public string name { get; set; }
public virtual Bookmark bookmark { get; set; }
public string user { get; set; }
Controller:
public ActionResult Edit(int id)
{
var editBookmark = adc.Bookmarks.Single(x => x.id == id);
var query_where2 = from a in adc.Tags
where a.bookmark.id == id
select a;
BookmarkTag bkTag = new BookmarkTag();
bkTag.bookmark = new List<Bookmark>();
bkTag.bookmark.Add(editBookmark);
bkTag.tag = query_where2.ToList();
return View(bkTag.tag);
}
//
// POST: /SavedBookmark/Edit/5
[HttpPost]
public ActionResult Edit(int id, ICollection<FormCollection> tag)
{
try
{
return View();
}
catch
{
return View();
}
Html code:
#using (Html.BeginForm("edit", "SavedBookmark"))
{
#Html.AntiForgeryToken()
if (Model != null) {
var aa= Model.First();
#Html.TextBox("test2", aa.bookmark.url);
List<BookIT2.Models.Tag> allTags = new List<BookIT2.Models.Tag>();
allTags = Model.ToList();
for (int i = 0; i < allTags.Count; i++)
{
if (!allTags[i].name.IsEmpty())
{
#Html.TextBox(allTags[i].name, allTags[i].name);
#Html.Hidden(allTags[i].id.ToString(), allTags[i].id);
#Html.Hidden(allTags[i].user, allTags[i].user)
#Html.Hidden(allTags[i].bookmark.id.ToString(), allTags[i].bookmark.id.ToString())
}
}
#Html.Label("Additional tag")
#Html.TextBox("additionalTag")
<input type="submit" value="edit" />
}
In short: I can't get any values in the http post ICollection, it's always null.
Here is the updated code:
#using (Html.BeginForm("edit", "SavedBookmark"))
{
#Html.AntiForgeryToken()
if (Model != null)
{
for (int i = 0; i < Model.tag.Count; i++)
{
if (!Model.tag[i].name.IsEmpty()) {
#Html.Hidden(Model.tag[i].id.ToString(), Model.tag[i].id);
#Html.Label("name");
#Html.TextBox(Model.tag[i].name, Model.tag[i].name);
#Html.Hidden(Model.tag[i].bookmark.id.ToString(), Model.tag[i].bookmark.id);
#Html.Hidden(Model.tag[i].user, Model.tag[i].user);
}
}
#Html.TextBox(Model.bookmark.id.ToString(), Model.bookmark.url);
<input type="submit" value="edit" />
}
}
Model class:
public class TestBookmark
{
public Bookmark bookmark{get; set;}
public List<Tag> tag {get; set;}
}
[HttpPost]
public ActionResult Edit(TestBookmark edit)
{}
Don't really understand why you're doing it this way. I would like to suggest you totally different approach.
First:
Create a class with all the fields you want in your view.
Second:
Use this class as the MODEL in your View
Third:
In the controller, in the POST function user your class as the only one parameter of that function.
I have this viewmodel that has some properties and stuff that i would like to apply
to the layoutpage:
public class BasicViewModel
{
public Page Page { get; set; }
public List<Settings> Settings { get; set; }
}
From other threads here have i understood that this is possible but i dont really understand how.
From what I understand I somehow need to modify a controller and this is where I get confused. How do I know what controller that has to be modified and how?
Any help appreciated.
In controller, Prepare an action like
public ActionResult BasicViewModelDemo
{
BasicViewModel obj=new BasicViewModel()
// assign properties
return View(obj);
}
and view write some jquery. (Here i am using knockout to make view model)
<script>
var model='#Html.Raw(Json.Encode(Model))';
var viewmodel = ko.mapping.fromJSON(model);
</script>
Here goes my solution -
Lets say you have a model of this way -
public class BasicViewModel
{
public Page Page { get; set; }
public List<Settings> Settings { get; set; }
}
public class Page
{
public string PageName { get; set; }
}
public class Settings
{
public string SettingName { get; set; }
}
Then in the controller you should initiate the model in this way -
public class HomeController : Controller
{
BasicViewModel model;
public HomeController()
{
model = new BasicViewModel();
model.Page = new Page();
model.Settings = new List<Settings>();
}
public ActionResult Index()
{
model.Page.PageName = "My Page";
ViewBag.LayoutModel = model;
return View();
}
}
So basically we used Constructor to initiate the model and then we assign proper values in the controller action.
Then in the Layout, we can use the Model property as shown below -
<div> #ViewBag.LayoutModel.Page.PageName </div>
I am trying to upload an image to a SQL database using ASP.NET MVC. The database BeforeImage remains as null although I am receiving no error a few file sizes and formats. Thanks
public class Job
{
public int ID { get; set; }
public byte[] BeforeImage { get; set; }
public byte[] AfterImage { get; set; }
}
View model:
public class BeforePhotoVM
{
public int ID { get; set; }
public HttpPostedFileBase BeforeImage { get; set; }
}
Get:
public ActionResult AddBefore(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var job = db.Jobs.Find(id);
var BeforeVM = new BeforePhotoVM();
//vm = db.Jobs.Find(id);
return View("Job2", BeforeVM);
}
Post:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddBefore([Bind(Include = "ID,BeforeImage")] BeforePhotoVM BeforeVM)
{
var job = db.Jobs.Find(BeforeVM.ID);
if (ModelState.IsValid)
{
byte[] BeforeImage = new byte[BeforeVM.BeforeImage.InputStream.Length];
BeforeVM.BeforeImage.InputStream.Read(BeforeImage, 0, BeforeImage.Length);
job.BeforeImage = BeforeImage;
db.Entry(job).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("AddBefore", new { id = job.ID });
}
return View("Job");
}
Look, you are doing too many things for something that should be simple.
Plus, next time, post ur html code with ur ajax.
Let me try to help you.
At your asp.net page.
your Html.Begin form should have the enctype = "multipart/form-data"
like this
#using (Ajax.BeginForm("Here goes ur action", "Here goes ur controller", new AjaxOptions { OnSuccess = "something with sucess" }, new { enctype = "multipart/form-data" }))
with that in mind
lets got to ur model
public byte[] Photo { get; set; }
ok ... now lets finish with the controller
public ActionResult Cadastro(YOURMODEL _model, HttpPostedFileBase file)
{
_model.Photo = new byte[file.ContentLength];
see, ur controller recives the HttpPostedFileBase and u can access creating a new byte.. but remember.. in ur asp.net code the file name has to be the same in ur controller as it bellow
The rest is with u
Hope this will help you.
I have DropDownList that read fils from my database and show this files in my DropDownList.
The current solution is show on my DropDownListItem System.Web.Mvc.SelectList instead of my Object property. I want to include a drop down list of my object (read from database) across my webpage.
This is my object:
public class MyObject
{
public int id { get; set; }
public string fileName { get; set; }
public string browser { get; set; }
public string protocol { get; set; }
public string family { get; set; }
}
My controller:
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
ViewBag.Files = lList;
return View();
}
Index.cshtml
#Html.DropDownList("File",new SelectList(ViewBag.Files))
What i want to see in my DropDownList is my protocol property.
Try like this:
#Html.DropDownList("File", new SelectList(ViewBag.Files, "id", "fileName"))
Try this
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").DistinctBy(x=> x.protocol).ToList();
ViewBag.Files = new SelectList(list,"Id","protocol");
return View();
}