i have a model SiteMapModel that have a object VirtualFolderModel inside him.
public class SiteMapModel
{
public SiteMapModel(DataRow data)
{
SMF_ID = Convert.ToInt32(data["SMF_ID"]);
SMF_VF_ID = Convert.ToInt32(data["SMF_VF_ID"]);
VirtualFolder = new VirtualFolderModel(data);
}
public VirtualFolderModel VirtualFolder;
public int SMF_ID { get; set; }
public int SMF_VF_ID { get; set; }
}
public class VirtualFolderModel
{
public VirtualFolderModel(DataRow data)
{
VF_ID = Convert.ToInt32(data["VF_ID"]);
}
public int VF_ID { get; set; }
}
in my controller i pass the model to a view.
public ActionResult Edit(int id)
{
SiteMapData smd = new SiteMapData();
SiteMapModel smm = new SiteMapModel(smd.GetFolderData((int)id, 15));
return View(smm);
}
how to use it in my view?
<div>
<span class="editor-label">
#Html.Label("Title")
</span>
#Html.TextBox("SMF_Name")
#Html.ValidationMessage("SMF_Name")
<span class="editor-label">
#Html.Label("VF_ID")
</span>
#Html.TextBox("VF_ID")
#Html.ValidationMessage("VF_ID")
<input type="submit" value="Save" />
</div>
the #Html.TextBox("VF_ID") don't work
At the top of your view add this:
#ModelType SitemapModel
Edit: For C# please use:
#model SitemapModel
Doing that will simply tell your view what kind of model is given at runtime. In this case, it's an object of type SitemapModel.
In your view you can reference to it to model.SMF_ID
Related
can't find whats wrong and can't find answer anywhere. My problem is my view not updated after view model have bean changed
ViewModel:
public class OrderView
{
public Customer Customer { get; set; }
public Order Order { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
public List<string> DomenNames { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
}
Controller:
private OrderView ov;
public ActionResult Index()
{
return View(ov);
}
[HttpPost]
public ActionResult Index(OrderView model, FormCollection collection) {
return View("done");
}
public ActionResult BlankEditorRow(OrderView model) {
ov = model;
ov.Order.DomenNames.Add("");
return View("Index",ov) ;
}
View:
#using (Html.BeginForm("Index","Order",FormMethod.Post, new {id = "createOrder"})) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Order</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Order.DomenNames)
</div>
#for(int i = 0; i < Model.Order.DomenNames.Count; i++) {
<div>
#Html.EditorFor(item => item.Order.DomenNames[i])
</div>
}
<button type="button" id="b1" onclick="setallert()" >Click me</button>
...
and script:
<script type="text/javascript">
function setallert() {
$.ajax({
url: "Order/BlankEditorRow",
data: $('#createOrder').serialize(),
cache: false,
success: function (data) {
...?
}
});
};
</script>
it goes fine to pass model to controller and while debugging through view I can see that model is changed, but in some case it nothing happen in view. It looks like old model is in place.
I have solved my problem. I post my solution in case some one need it:
Controller:
public ActionResult BlankEditorRow(OrderView model) {
model.Order.DomenNames.Add("");
return PartialView("Index", model) ;
}
View:
<div class="editor-label">
#Html.LabelFor(model => model.Order.DomenNames)
</div>
<div id="tt">
#{Html.RenderPartial("OrderDN", this.Model);}
</div>
<button type="button" id="addBtn">Click me</button>
Script:
$("#addBtn").click(function () {
$.get('#Url.Action("BlankEditorRow", "Order")', $('#createOrder').serialize(), function (res) {
document.getElementById("tt").innerHTML = res;
});
})
I hope it will be useful to someone
How to get data from two table or two class in single view in mvc3.
I want to show data from both the table.
I have one parent class and two child class.
i.e
public class GetDocumentParent
{enter code here
public List getDocument { get; set; }
public List getDocumentRevision { get; set; }
}
View:
" %>
<% foreach (var item in Model.getDocument)
{ %>
<tr>
<td>
<%:Html.DisplayFor(ModelState => item.DOCUMENT_NAME)%>
</td>
<td>
<%:Html.DisplayFor(ModelState => item.ActiveDate)%>
</td>
<td>
<%:Html.DisplayFor(ModelState => item.Revision)%>
</td>
<td>
</tr>
<% } %>
==>item.DOCUMENT_NAME and item.ActiveDate from Document Class.
item.Revision from Document_Revision class.
how to show both class's value at the same time in view.
Controller:
var model = new GetDocumentParent
{
getDocument = db.Document.ToList(),
getDocumentRevision = db.DocumentRevisions.ToList()
};
return View(model);
Model:
1.
public class DOCUMENTS
{
public string DOCUMENT_NAME
{
get;
set;
}
public Nullable<System.DateTime> ActiveDate
{
get;
set;
}
}
2.
public class DOCUMENT_REVISIONS
{
public string REVISION
{
get;
set;
}
}
Thanks in advance
Always remember that it is best to have a view model that represents your data that is sent to the view. The view will do what is needed with you view model. The code below can guide you, you must just change it to fit into your scenario.
Lets say that I have a customer and each customer has only 1 address. I would create a view model called CustomerDetailsViewModel to represent this data:
public class CustomerDetailsViewModel
{
public string FirstName { get; set; }
public string Lastname { get; set; }
public int Age { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
}
Your action method to display the customer and customer address details:
public class CustomerController : Controller
{
private readonly ICustomerRepository customerRepository;
public CustomerController(ICustomerRepository customerRepository)
{
// Check customerRepository for nulls
this.customerRepository = customerRepository;
}
public ActionResult Details(int id)
{
// Check that id is not zero or negative
Customer customer = customerRepository.GetById(id);
// Get the customer's address
Address address = customerRepository.GetCustomerAddress(id);
CustomerDetailsViewModel viewModel = new CustomerDetailsViewModel()
{
FirstName = customer.Firstname,
LastName = customer.LastName,
Age = customer.Age,
AddressLine1 = address.AddressLine1,
AddressLine2 = address.AddressLine2,
City = address.City
}
return View(viewModel);
}
}
id above represents your customer's unique identifier. It is used to return a cusotmer:
Customer customer = customerRepository.GetById(id);
and also used to returned a specific customer's address:
Address address = customerRepository.GetCustomerAddress(id);
An ICustomerRepository instance is injected by an IoC container for example Autofac.
In your view you pass this view model as such and can display the data as you please:
#model MyProject.DomainModel.ViewModels.Customers.CustomerDetailsViewModel
<div class="content">
<div class="display-label">First Name: </div>
<div class="display-content">#Model.FirstName</div>
<div class="display-label">Last Name: </div>
<div class="display-content">#Model.LastName</div>
<div class="display-label">Age: </div>
<div class="display-content">#Model.Age</div>
<div class="display-label">Address Line 1: </div>
<div class="display-content">#Model.AddressLine1</div>
<div class="display-label">Address Line 2: </div>
<div class="display-content">#Model.AddressLine2</div>
<div class="display-label">City: </div>
<div class="display-content">#Model.City</div>
</div>
I hope this helps.
What is the problem?
use in controller:
var model = new GetDocumentParent();
model.getDocument = ...//Code that initialize getDocument
model.getDocumentRevision =...//Code that initialize getDocumentRevision
in View:
#Html.EditorFor(m=>m.getDocument);
#Html.EditorFor(m=>m.getDocumentRevision);
I can't find a sample with this simple problem.
I have 2 tables Books and Authors with a foreign key on AuthorID.
I need to be able to add a book with an author and that author to be inserted with the foreign key relation.
Is it possible from an create view and controller in MVC?
These are models:
namespace CiksAyna.Data.Model
{
[TableName("tbl_book")]
[PrimaryKey("book_id", autoIncrement = true)]
public class Book
{
[Column("book_id")]
public int BookId { get; set; }
[Column("author_id")]
public int AuthorId { get; set; }
}
}
namespace CiksAyna.Data.Model
{
[TableName("tbl_author")]
[PrimaryKey("author_id", autoIncrement = true)]
public class Author
{
[Column("author_id")]
public int AuthorId { get; set; }
[Column("author_name")]
public int AuthorName { get; set; }
}
}
In view page
#model CiksAyna.Data.Model.Book
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Books</legend>
<div class="editor-field">
#Html.DropDownListFor(model => model.AuthorId, new SelectList(ViewBag.Authors, "AuthorId", "AuthorName"))
#Html.ValidationMessageFor(model => model.AuthorId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
In controller
public ActionResult Create()
{
ViewBag.Authors = GetAllAuthors();
return View();
}
public List<Author> GetAllAuthors()
{
return Db.From("tbl_author").ToList<Author>();
}
I hope someone can help with this one. I have three Model classes like this:
public class Provider
{
public Guid ProviderId { get; set; }
public string Name { get; set; }
public Guid LocationId { get; set; }
public virtual Location Location { get; set; }
}
public class Location
{
public Guid LocationId { get; set; }
public string NameOrCode { get; set; }
public string Description { get; set; }
public string StreetNumber { get; set; }
public string StreetAddress1 { get; set; }
public string StreetAddress2 { get; set; }
public string City { get; set; }
public int? StateId { get; set; }
public string Zip { get; set; }
public string ContactPhone { get; set; }
public virtual State State { get; set; }
}
public class State
{
public int StateId { get; set; }
public string Name { get; set; }
public string Abbreviation { get; set; }
}
As you can see, a Provider has a Location (separate class for reuse elsewhere), and a Location has a State (which is null until selected).
My Controller looks like this for my Create methods:
public class ProviderController : BaseController
{
private SetupContext db = new SetupContext();
// other CRUD methods ...
//
// GET: /Provider/Create
public ActionResult Create()
{
Location location = new Location()
{
LocationId = Guid.NewGuid(),
NameOrCode = Resources.BillingLocation,
Description = Resources.BillingLocationDescription
};
Provider provider = new Provider()
{
ProviderId = Guid.NewGuid(),
LocationId = location.LocationId,
Location = location
};
ViewBag.StateId = new SelectList(db.States, "StateId", "Name", provider.Location.StateId);
return View(provider);
}
//
// POST: /Provider/Create
[HttpPost]
public ActionResult Create(Provider provider)
{
if (ModelState.IsValid)
{
db.Locations.Add(provider.Location);
db.Providers.Add(provider);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.StateId = new SelectList(db.States, "StateId", "Name", provider.Location.StateId);
return View(provider);
}
// other CRUD methods ...
}
Finally, my View looks like this:
<div class="editor-label">
#Html.LabelFor(model => model.Location.StateId, #Resources.Location_State_Display_Name)
</div>
<div class="editor-field">
#Html.DropDownList("StateId", #Resources.ChooseFromSelectPrompt)
#Html.ValidationMessageFor(model => model.Location.StateId)
</div>
My problem is that the state the user selects in the DropDownList never gets set on my Model on the Create POST. I have similar code in my Edit View and the state is populated correctly in that View (that is, the state associated with an existing Provider.Location shows selected in the DropDownList for the user to edit if desire), but in both the Create and the Edit Views the selection made by the user is never registered in my Model (specifically the Provider.Location.StateId) coming in from the POST.
Looking at the HTML produced I see this:
<div class="editor-label">
<label for="Location_StateId">State/Territory</label>
</div>
<div class="editor-field">
<select id="StateId" name="StateId"><option value="">[Choose]</option>
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<!-- more options ... -->
</select>
<span class="field-validation-valid" data-valmsg-for="Location.StateId" data-valmsg-replace="true"></span>
</div>
I suspect I need to somehow convey the Location.StateId relationship instead of just StateId as I see above but I can't figure out the correct syntax to do that. I've tried changing my ViewBag dynamic property to Location_StateId like this:
ViewBag.Location_StateId = new SelectList(db.States, "StateId", "Name", provider.Location.StateId);
And the DropDownList in my View like this:
#Html.DropDownList("Location_StateId", #Resources.ChooseFromSelectPrompt)
I figured then perhaps that notation would work because the label beside my DropDownList was rendered as:
<div class="editor-label">
<label for="Location_StateId">State/Territory</label>
</div>
This attempt did not work. Can you help me out?
Thanks in advance.
#Html.DropDownList("Location.StateId", #Resources.ChooseFromSelectPrompt)
Also the following line doesn't do anything useful:
ViewBag.StateId = new SelectList(db.States, "StateId", "Name", provider.Location.StateId);
You are assigning a SelectList to something that is supposed to be a scalar property. You probably wanted to pass the collection as ViewBag:
ViewBag.States = new SelectList(db.States, "StateId", "Name", provider.Location.StateId);
and then in the view:
#Html.DropDownList("Location.StateId", (SelectList)ViewBag.States)
How do I use MVC3 editor templates for lists with add and delete?
I have an object:
public class Policy
{
public List<PolicyLine> PolicyLines = new List<PolicyLine>();
}
public class PolicyLine
{
public PolicyLine(bool isPositive, string policyText)
{
IsPositive = isPositive;
PolicyText = policyText;
}
public bool IsPositive { get; set; }
public string PolicyText { get; set; }
}
I have an editorTemplate: in Views\Shared\EditorTemplates\Policy.cshtml and Views\Shared\EditorTemplates\PolicyLine.cshmtml and I'm wondering how to enable users to add and delete PolicyLines from the Policy?
For the DELETE, just add the following line to the PolicyLine.cshtml and add a Delete Action to your Controller to perform the delete.
#Html.ActionLink("Delete", "Delete", new { id = #Model.PolicyID })
The ADD is a bit trickier, you could add button to you Policy.cshtml and then call some javascript to insert some html on the fly.
OR
You could have the button display a new page to capture the new policyline and then return to the original page with the new line added.
I got this to work for me:
Here is my Views/Policy/Index.cshtml
#using (Html.BeginForm("Submit", "Policy")) {
<fieldset>
#Html.EditorForModel()
</fieldset>
}
Here is my Views/Shared/EditorTemplates/Policy.cshtml
#model Policy
<br />
<label for="IsPositive">Is positive?</label>
#Html.CheckBox("IsPositive")
<input type="text" name="PolicyText" />
<input type="submit" value="Add to Policy" title="SubmitFromReferalPolicy" />
#Html.EditorFor(a => a.PolicyLines)
Here is my Views/Shared/EditorTemplates/PolicyLine.cshtml
#model PolicyLine
<br />
#this.Model.ToString()
#Html.ActionLink("Delete", "DeleteLine/" + Model.Identifier.ToString())
Here is my Policy.cs
public class Policy
{
public string Id { get; set; }
public List<PolicyLine> PolicyLines = new List<PolicyLine>();
public override string ToString()
{
return PolicyFormatter.FormatPolicy(this);
}
}
Here is my PolicyLine.cs
public class PolicyLine
{
public bool IsPositive { get; set; }
public string PolicyText { get; set; }
public Guid Identifier { get; set; }
public override string ToString()
{
return PolicyFormatter.FormatPolicyLine(this);
}
}
Here is my add method from PolicyController.cs
[HttpPost]
public ActionResult Submit(PolicyLine submitted)
{
Policy saveMe = Policy.GetPolicyFromUserName(UserName);
submitted.Identifier = Guid.NewGuid();
saveMe.PolicyLines.Add(submitted);
Store.Write(saveMe);
return RedirectToAction("Index");
}
Here is my delete method from PolicyController.cs
public ActionResult DeleteLine(Guid identifier)
{
Policy saveMe = Policy.GetPolicyFromUserName(UserName);
PolicyLine removeMe = saveMe.PolicyLines.Find(p => p.Identifier == identifier);
saveMe.PolicyLines.Remove(removeMe);
Store.Write(saveMe);
return RedirectToAction("Index");
}