how to set default value HTML.TextBoxFor() - asp.net-mvc

I have a view consisting of a form and textboxes.
How can I set a default value in each box for strings and int values?
I want the page to load up each box's value so I don't need to type values.
I'm not able to change anything in the Model.
#model MyDb.Production.ProductionMaterial
#{
ViewBag.Title = "CreateMaterial";
}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>ProductionOrderMaterial</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Position)
</div>
<div class="editor-field"> //something like
#Html.TextBoxFor(model => model.Position, Or 5 )
#Html.ValidationMessageFor(model => model.Position)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ArticleId)
</div>
<div class="editor-field"> //something like
#Html.TextBoxFor(model => model.ArticleId. Or "")
#Html.ValidationMessageFor(model => model.ArticleId)
</div>
}

Create an instance of the model in your action, assign some values to the properties of the model and pass that into the View method.
In your action have:
ProductionMaterial model = new ProductionMaterial();
model.Position = 5;
return this.View(model);
This will pass the model to the view and TextBoxFor( model => model.Position ) will display 5.

I see you already got answer, but I'll show you how you can do it another way:
In Controller
public ActionResult Index()
{
//here you must set VALUE what u want,
//for example I set current date
Viewbag.ExactlyWhatYouNeed = DateTime.Now
return View();
}
In View
#Html.TextBoxFor(model => model.CurrentDate, new { #Value = ViewBag.ExactlyWhatYouNeed})
And when you will load your View, you will get field with default value (current date in our example)
Its work on MVC 4
Hope Its will be usefull info for another people.

Related

Passing data from a View to a Controller in .NET MVC - "#model" not highlighting

The following code works as I need it to:
#using (Html.BeginForm("LOLOL", "PATIENT", null))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>PATIENT</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</fieldset>
<p>
<input type="submit" value="SUBMIT" />
</p>
}
In LOLOLController:
[HttpPost]
public IActionResult LOLOL(Patient p) {
var client = new MongoClient("mongodb://localhost:27017");
var userId = _userManager.GetUserId(HttpContext.User);
string db_name = "test" + userId;
var database = client.GetDatabase(db_name);
var collection = database.GetCollection<BsonDocument>("patients");
var filter = Builders<BsonDocument>.Filter.Eq("Name", p.Name.ToString());
var document = collection.Find(filter).First();
// I'm cutting short the rest of the code, because when I do something
// similar later, "collection.Find(filter).First()" fires an exception, I'll
// explain..
return View(p);
}
I have something equivalent to taking off the fieldset element in the HTML, leaving basically just a button in the "Html.BeginForm", but then the data is clearly not binding properly, which I know because if I just have a button and no data-entry, I click the button and then I get an error saying the data cannot be found from the database. (EDIT: I now have confirmed that this is indeed because the Patient object is not being passed to the controller quite as I expected it to, seems like a brand new Patient object was created upon calling html.beginform ... I thought that maybe the old Patient object was being passed so I did not have to enter all its data members every time we use Html.BeginForm)
In sum, I want to fill out a text box, click a button to load a new page and display the value of that textbox, but have that value also persisted in essentially a session state, so that if I call another Html.BeginForm function and go into a third view, the text from the first view will be displayed in the third view, even though I did not have to type its value in the second view. Hopefully I can repeat this process, and essentially load up the data members of a class with one view per data member.
Make sure you pass the data from the previous view to the new view from your Controller. When you pass it, include #HiddenFor for those properties from the previous view in your new view. That way the new view will keep and then pass the values to your next POST.
#Html.HiddenFor(model => model.PropertyYouPassedAndWantToKeepAndPassAgain
Edit: Here's the logic for using multiple views for one object... as requested.
Model:
public class Patient
{
string Name { get; set; }
string Address { get; set; }
string City { get; set; }
}
Page1 GET:
[HttpGet]
public ActionResult Page1()
{
Patient patient = new Patient();
return View("~/Views/Page1.cshtml", patient);
}
Page 1 View... only ask for the name.
#model mysite.Models.Patient
#using (Html.BeginForm("LOLOL", "PATIENT", null))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>PATIENT</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</fieldset>
<p>
<input type="submit" value="SUBMIT" />
</p>
}
Page1 POST... get the patient and pass it on to the next view...
[HttpPost]
public ActionResult Page1(Patient patient)
{
if (ModelState.IsValid)
{
return View("~/Views/Page2.cshtml", patient); // pass your patient to the second page view with the name
}
else
{
return View("~/Views/Page1.cshtml", patient);
}
}
Page2 GET... get the patient from the prior Page1 POST and send it off to the Page2 View.
[HttpGet]
public ActionResult Page2(Patient patient)
{
// Receive patient from Page1 post and pass it to new view... includes the name
return View("~/Views/Page2.cshtml", patient);
}
Page2 View gets the object... use a HiddenFor to keep the name which you just sent from the GET.
#model mysite.Models.Patient
#using (Html.BeginForm("LOLOL", "PATIENT", null))
{
#Html.HiddenFor(model => model.Name) #* This will keep the name on your next post *#
#Html.ValidationSummary(true)
<fieldset>
<legend>PATIENT</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
</fieldset>
<p>
<input type="submit" value="SUBMIT" />
</p>
}
Since the HiddenFor holds the Name, it will be passed on your next post. It is there but hidden from the form itself.
[HttpPost]
public ActionResult Page2(Patient patient)
{
// Because of the HiddenFor, the Name will be passed because it was kept in the view... but hidden from the form itself.
// It's basically storing it for you to pass again
if (ModelState.IsValid)
{
// Pass object with Name and Address to next controller
return View("~/Views/Page3.cshtml", patient);
}
else
{
return View("~/Views/Page2.cshtml", patient);
}
}
Page2 POST
[HttpPost]
public ActionResult Page2(Patient patient)
{
// Because of the HiddenFor, the Name will be passed because it was kept in the view... but hidden from the form itself.
// It's basically storing it for you to pass again
if (ModelState.IsValid)
{
// Pass object with Name and Address to next controller
return View("~/Views/Page3.cshtml", patient);
}
else
{
return View("~/Views/Page2.cshtml", patient);
}
}
Page3 GET
[HttpGet]
public ActionResult Page3(Patient patient)
{
// Pass patient again... to your next view
return View("~/Views/Page3.cshtml", patient);
}
Page3 View...
#using (Html.BeginForm("LOLOL", "PATIENT", null))
{
#Html.HiddenFor(model => model.Name) #* Keep name again for your next post *#
#Html.HiddenFor(model => model.Address) #* Now we are keeping the address as well *#
#Html.ValidationSummary(true)
<fieldset>
<legend>PATIENT</legend>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</div>
</fieldset>
<p>
<input type="submit" value="SUBMIT" />
</p>
}
And so on and so forth... until you have your model complete and want to do something with it.

MVC Data Model from URL to Controller

Hi i need to pass some data from an URL to a controller in MVC. The data are in #Value = #Request.QueryString["rt"] in this code:
#using (Html.BeginForm("ResetPasswordToken", "Account")){
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "Reset Password non riuscito")
<div class="container above-footer login-form">
<div class="col-md-6" align="center" style=" margin-left:25%; margin-top:100px; margin-bottom:100px;">
<div class="editor-label">
#Html.LabelFor(m => m.ResetToken)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.ResetToken, new { #Value = #Request.QueryString["rt"] })
#Html.ValidationMessageFor(m => m.ResetToken)
</div>
And i need to retrieve this value in the AccountController when i go on the submit button associated to this view. What is the best mode to do this without see it in the page?
I know is a very simple question but i need to do only this modification for tomorrow and i am very busy. Thanks to all and sorry for the question
In the controller action that rendered this view (the GET action):
model.ResetToken = Request["rt"];
return View(model);
and then in the view simply:
#Html.TextBoxFor(m => m.ResetToken)
or if you don't want this to be shown in the form you could also use a hidden field:
#Html.HiddenFor(m => m.ResetToken)
Now when the form is submitted back to the ResetPasswordToken action you can read this value from the model:
[HttpPost]
public ActionResult ResetPasswordToken(MyViewModel model)
{
// you can use the model.ResetToken property here to read the value
}
Alternatively you could include this value as part of the url when generating the action attribute of your HTML form:
#using (Html.BeginForm("ResetPasswordToken", "Account", new { ResetToken = Request["rt"] }))
{
...
}

How can you do multiple saves of a model in one submit?

I have a model:
public class CustomerAttributes
{
public Int Id { get; set; }
public string value { get; set; }
}
my create view looks like this:
<div class="editor-label">
#Html.Label("Name")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Value)
#Html.ValidationMessageFor(model => model.Value)
</div>
<div class="editor-label">
#Html.Label("Age")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Value)
#Html.ValidationMessageFor(model => model.Value)
</div>
<div class="editor-label">
#Html.Label("Height")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Value)
#Html.ValidationMessageFor(model => model.Value)
</div>
So each textbox will be a new record in the database. Is it possible to do something like this? How can I handle this? Also my biggest problem is that each field could be a textbox or a combobox or a radio.... etc... Name might a textbox for example but age might be a combobox.... I know I have all textboxes now but that could change.
I would personally suggest creating a IEnumerable ViewModel of your CustomerAttributes model.
This way you could pass multiple values back to the controller.
Each time you added the new form elements (assuming you are adding them dynamically), you would just create a new item within the model.
The link provided in a comment was helpful:
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
To add to that, there could be a ViewModel that can hold a string or an enum or something to specify what type of control to display and with that some partial views that display the different controls. Then iterate through and display each control in the view based on that specifier.

adding new comment in database for a post

I am creating a forum application in mvc3...
I have a link called Add New Comment on Post page where user can add the comments for that post... for creating new comment i have written following code....
public ActionResult Addnew(int id)
{
Answer ans = new Answer();
ans.QuestionQId = id;
return View();
}
[HttpPost]
public ActionResult Addnew(Answer ans,int id)
{
_db.Answers.Add(ans);
_db.SaveChanges();
return View("Details");
}
but it is giving mean error whenever i try to save the code as follows:
Value cannot be null.
Parameter name: entity
I have two different table Question{id(pk), Question} and Answer{id(pk), ans, Qid(fk)}
All i want to do is While adding the comment for a perticular question, its Qid will be stored in answer database .....
Help me!!
View Related --
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Answer</legend>
<div class="editor-label">
#Html.LabelFor(model => model.AId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AId)
#Html.ValidationMessageFor(model => model.AId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Ans)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Ans)
#Html.ValidationMessageFor(model => model.Ans)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.QuestionQId)
</div> <div class="display-field">
#Html.DisplayFor(modelItem => modelItem.QuestionQId)
</div>
}
I think you are not passing the Answer object to the view, may caused the problem. have you tried following
public ActionResult Addnew(int id)
{
Answer ans = new Answer();
ans.QuestionQId = id;
return View(ans);
}
is it in your route define parameter for your controller?
may be this is your problem!

No value for the dropdownlist when my form is submitted

I try to use a dropdownlist in my view for showing a list of authors (users). I'm able to populate this dropdown and see the content in my view. When submitting my form, I debug my action in my controller and when inspecting my model, the value of the field associated with my dropdown is null.
Here is my action controller (before showing my view):
public ActionResult Create()
{
IEnumerable<User> authors = m_AccountBusiness.GetAllUsers();
PageCreateViewModel viewModel = new PageCreateViewModel
{
PageToCreate = new PageFullViewModel(),
Authors = authors.Select(x => new SelectListItem { Text = x.UserName, Value = x.UserID.ToString() })
};
return View(viewModel);
}
Here is (a portion of) my view:
#model MyBlog.ViewModels.PageCreateViewModel
<h3>Create</h3>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.PageToCreate.PageID)
<div class="editor-label">
#Html.LabelFor(model => model.PageToCreate.Title)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PageToCreate.Title, new { #class = "titleValue" })
#Html.ValidationMessageFor(model => model.PageToCreate.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PageToCreate.Author)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.PageToCreate.Author, Model.Authors, "Please select...")
</div>
Here is my PageCreateViewModel:
public class PageCreateViewModel
{
public PageFullViewModel PageToCreate { get; set; }
public IEnumerable<SelectListItem> Authors { get; set; }
}
Any idea?
Thanks.
Thank you guys. I finally found my error: it is not Author the right property to bind to, it must be AuthorID !!
<div class="editor-field">
#Html.DropDownListFor(model => model.PageToCreate.AuthorID, Model.Authors, "Please select...")
</div>
Thanks anyway.
You have to add an extra string property to your PageCreateViewModel. In this property we will store the selected value. Lets say it's name is "Author". Edit: I noticed you have a property for it in your model but give it a try like this.
The dropdownlist filling needs to look like this on your view.
#Html.DropDownList("Author", Model.Authors)

Resources