My project is Room-reservation service .I have View :
#model Client
#using (Html.BeginForm("SaveUserDB", "Booking", FormMethod.Post))
{
<div class="editor-label">
#Html.Label("Surname")
#Html.TextBoxFor(model => model.Surname)
</div>
<div class="editor-label">
#Html.Label("Name")
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.Label("Patronymic")
#Html.TextBoxFor(model => model.Patronymic)
</div>
<input type="submit" id="submit" value="Reservation" />
And I have controller for this View:
[HttpPost]
public ActionResult SaveUserDB(Client client)
{
if (ModelState.IsValid)
{
using (db)
{
db.Client.Add(client);
db.SaveChanges();
return RedirectToAction("Thankyou");
}
}
return View(client);
}
This controller save data client to database table Client. But I need also create record in second table Reservation, which takes parameters: Datetime.Now , and Client.Id. Parameter Client Id in database is autoincrement, but doesn't display in the View.
Well, if this is how you add a record to the Client table:
db.Client.Add(client);
Then why not use that same exact approach to add a record to the Reservation table? Something like this:
var reservation = new Reservation
{
ClientID = client.ID,
SomeOtherColumn = DateTime.Now
};
db.Reservation.Add(reservation);
(Note: This is based on speculation of what your Reservation object/table might look like based on your description. But the concept is the same. Create an instance of a reservation object and add it to the data context.)
Related
I am working on ASP.Net MVC 4.7.2 app. It has a date field where user can select or type the date. If user enter the date with year yyyyy (the length of year is greater than 4 here)then the error shows up which show the date in 'yyyy/mm/dd' format instead of 'mm/dd/yyyy' format. See the screen shot below.
I want to show the same format in the error message as mm/dd/yyyy'. To fix the issue I did search and it seemed this is generated from kendu whereas I am not using the kendu control for date field. As a work around, I thought I can limit the max length but that did not work as well.
View html:
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-xs-2" })
<div class="col-xs-8">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
I try some research and seem like it's hard to change the error message with the right format. You can update the error message to "Please enter a valid date" or "Please enter a valid date with format mm/dd/yyyy"
#Html.EditorFor(model => model.Name, new
{
htmlAttributes = new { #class = "form-control" },
data_val_date = String.Format("Please enter a valid date",
Html.DisplayNameFor(model => model.Name))
})
I have a DDL which fetch data assigned users from DB. I want to give ability to type it in or select from DDL.
here is my view code
<div class="form-group col-md-6 ui-front">
<label class="control-label">Assigned To</label>
#Html.DropDownListFor(model => model.OpsMonUser, new SelectList(Model.OpsMonUser), new { #id =
"OpsMonUserDDL", #class = "form-control" })
</div>
Any idea how should I proceed further?
I am trying to pass two parameters through a #Url.Action for a submit button. However, the values are not being passed.
I have index view with a dropdown field and a Save button. What I would like for the user to be able to do is select a dropdown value and Save the value. However, no matter how I access my function the values are null. I have tried passing in parameters and binding the data.
Currently my view looks like -
<h3>Burn Conditions</h3>
<div class="form-group">
#Html.LabelFor(model => model.ConditionsReasonsID, "Condition", new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.DropDownList("ConditionsReasonsID", String.Empty)
#ViewBag.conditionsReasons
#Html.ValidationMessageFor(model => model.ConditionsReasonsID)
<a href= "#Html.Raw(#Url.Action("CreateCondition", "RequestedBurns", new { requestedBurnsID = ViewBag.RequestedBurnsID, conditionsReasonsID = Model.ConditionsReasonsID }))">
<input type="submit" value="Save Condition" />
</a>
</div>
</div>
in my controller I have
public ActionResult CreateCondition(int requestedBurnsID, int conditionsReasonsID)
{
BurnDecision burnDecision = new BurnDecision();
burnDecision.RequestedBurnsID = requestedBurnsID;
burnDecision.ConditionsReasonsID = conditionsReasonsID;
//Find BurnSiteID
RequestedBurn requestedBurn = db.RequestedBurns.Find(burnDecision.RequestedBurnsID);
ViewBag.burnSitesID = requestedBurn.BurnSitesID;
db.BurnDecisions.Add(burnDecision);
db.SaveChanges();
return RedirectToAction("Index", "RequestedBurns", new { burnSitesID = ViewBag.burnSitesID, requestedBurnsID = burnDecision.RequestedBurnsID });
}
Disclaimer: I'm brand new to Razor. I can't seem to figure out the following:
When I use #Html element inside #Section, I get the following compilation error
An expression tree may not contain a dynamic operation.
Here is my Code:
#section login{
#using (Html.BeginForm(new {ReturnUrl = ViewBag.ReturnUrl}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
#*<fieldset>
<legend>Log in Form</legend>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</li>
<li>
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe, new {#class = "checkbox"})
</li>
<input type="submit" value="Log in" />
</fieldset>*#
}
}
As you can see, I'm trying to put these elements inside html tags, but I've commented a lot of it to troubleshoot. Any input on why I'm getting this error and how to fix it would be greatly appreciated.
Thanks!
Add your model class (fully namedspaced) as a #model directive at the top of your view.
e.g.
#model myapplication.mynamespace.LoginModel
and your LoginModel looks like:
public class LoginModel
{
public string UserName {get; set;}
public string Password {get; set;}
public bool RememberMe {get; set;}
}
TextBoxFor, CheckboxFor etc use expression trees and reflection to get at the real value. Without a real model it has no clue what type of values to expect and therefore can't build an expression tree at compile time.
I hope there is a simple answer to this problem which I'm just not seeing.
I am developing an asp.net MVC 4 application.
Basically I want to allow the user to edit the contents of a previous entry(newsArticle) they would have made (sounds easy)
This entry consist's of a date, two blocks of text, (Title and body) an img.
These entries correspond to properties of a model, which also include, ID , img name and status.
I have successfully manged to enter, save and retrieve all the data when needed.
However when I run the program and try and edit a previous entry it only saves the Title and the body text and removes the values that were there, for date, img, img name and status.
Is this related to the textboxes used in the view ? Why are those values kept and the others not.
Just to point out when I run and select an entry all the data is shown correctly but when I click save values are removed (date, img name , status)
Any thoughts.....
Controller....
public ActionResult Edit(int id)
{
String encodedBody;
NewsArticle newsArticle = _newsArticle.Get(id);
encodedBody = HttpUtility.HtmlDecode(newsArticle.Body.ToString());
newsArticle.Body = encodedBody;
return View(newsArticle);
}
// POST: /Article/Edit/5
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle)
{
try
{
if (ModelState.IsValid)
{
db.Entry(newsArticle).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (System.Data.DataException)
{
//Log th error(add a variable name after DataExpection)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(newsArticle);
}
View.......
#using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form-horizontal", id = "newsEditForm"}))
{
#Html.ValidationSummary()
#Html.HiddenFor(model => model.ID)
<div class="control-group">
<label class="control-label">Posted on :</label>
<div class="controls">
<span class="text">#Model.DateCreated.Value.ToShortDateString()</span>
#*#Html.LabelFor(n => n.DateCreated)*#
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.LabelFor(n => n.Title)</label>
<div class="controls">
#Html.TextBoxFor(n => n.Title, new { #class = "span4 m-wrap", rows = 1})
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.LabelFor(n => n.Body)</label>
<div class="controls">
#Html.TextAreaFor(n => n.Body, new { #class = "span12 ckeditor m-wrap", rows = 4 })
</div>
</div>
<div class="control-group">
<label class="control-label">Selected Image </label>
<label class="controls">#Html.DisplayTextFor(model => model.ImageName)</label>
#* <div class="span4 blog-img blog-tag-data">
<div class="editor-field">
<input type="file" name="Article" id="ArticleImage"/>
</div>
</div>*#
</div>
<div class="form-actions">
<button type="submit" class="btn green" id="submitnews"><i class="icon-ok"></i>Submit</button>
#Html.ActionLink("Cancel", "ArticleList", "Admin", null, new { #class = "btn blue"})
#*<button type="button" class="btn blue" onclick="location.href='ArticleList','Admin'">Cancel</button>*#
</div>
}
Your problem is you're saving the newsArticle that's posted back directly to the DB. The posted newsArticle contains a null entry for the image, date, img name and status because those fields don't exist in your form. You really shouldn't pass domain models back to your edit for this and other security reasons. However, this is a quick fix to your issue
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle)
{
try
{
if (ModelState.IsValid)
{
NewsArticle savedArticle= _newsArticle.Get(newsArticle.Id);
savedArticle.Body = newsArticle.Body
savedArticle.Title = newsArticle.Title
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (System.Data.DataException)
{
//Log th error(add a variable name after DataExpection)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(newsArticle);
}