Display Model Data in View - c#

I am new to ASP.NET MVC and I am having trouble updating the model data and then displaying it my view.
I currently have a MortgageCalculator class that I am using as a model.
public double loan_amount { get; set; }
public double interest { get; set; }
public int loan_duration { get; set; }
public int payments_year { get; set; }
Code for the controller is:
[httpGet]
public ActionResult M_Calculator()
{
var mortgageCalculator = new MortgageCalculator();
return View(mortgageCalculator);
}
[HttpPost]
public ActionResult M_Calculator(MortgageCalculator mortgageCalculator)
{
UpdateModel(mortgageCalculator);
return RedirectToAction("Results");
}
public ActionResult Results (MortgageCalculator mortgageCalculator)
{
return View(mortgageCalculator);
}
Code for my view is:
#using (Html.BeginForm())
{
<fieldset>
<legend>Mortgage Calculator</legend>
<div class="editor-label">
#Html.LabelFor(model => model.loan_amount)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.loan_amount)
</div>
<br />
<div class="editor-label">
#Html.LabelFor(model => model.interest)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.interest)
</div>
<br />
<div class="editor-label">
#Html.LabelFor(model => model.loan_duration)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.loan_duration)
</div>
<br />
<div class="editor-label">
#Html.LabelFor(model => model.payments_year)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.payments_year)
</div>
<br />
<input type="submit" value="Calculate" />
</fieldset>
}
I want to make some calculations on the data that I receive from the user and then show the results in my Results view. I don't have any database. I just want to perform simple calculations on data and show the results. The solution seems to be pretty straight forward but I am stuck. I would appreciate any help.

Instead of redirect user to another action you should return your model with the result populated, like this:
[HttpPost]
public ActionResult M_Calculator(MortgageCalculator mortgageCalculator)
{
UpdateModel(mortgageCalculator);
return View("Results", mortgageCalculator);
}
If you don't want to create another view only to show the results, just remove the first parameter that indicates which view ASP.NET MVC should use, so, it will use the default view.

Related

mvc c# file upload as byte array

I have to upload files and other data in a single submit of UploadFile.cshtml form
I have a base class which is the input of mvc action in home controller.
My base class, mvc action method and cshtml part with Razor script is given below
I have to get the file as byte array in the mvc action while submitting the UploadFile.cshtml form
My Base class
public class FileUpload
{
public string Name {get;set;}
public int Age {get;set;}
public byte[] Photo {get;set;}
}
MyMVCAction
[HttpPost]
public void UploadFile(FileUploadobj)
{
FileUploaddata=obj;
}
Mycshtmlform
#modelMVC.Models.FileUpload
#using(Html.BeginForm("UploadFile","Home",FormMethod.Post))
{
<fieldset>
<legend>File Upload</legend>
<div class="editor-label">
#Html.LabelFor(model=>model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model=>model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model=>model.Age)
</div>
<div class="editor-field">
#Html.EditorFor(model=>model.Age)
</div>
<div class="editor-label">
#Html.Label("UploadPhoto");
</div>
<div class="editor-field">
<input type="file" id="photo" name="photo"/>
</div>
<p>
<input type="submit" value="Create"/>
</p>
</fieldset>
}
I think better achieve it like this:
[HttpPost]
public ActionResult UploadFile(FileUpload obj)
{
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
obj.Photo = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
//return some action result e.g. return new HttpStatusCodeResult(HttpStatusCode.OK);
}
I hope it helps.

ASP.NET Entity Manager: create more than one entity in a view

i want to to create a create-view where you have the possibility to enter a value for more than one entity - "a list of entities"
e.g. Entity Class
public class MyEntity{
public string myAttribute { get; set; }
}
For the View I created a ModelView which looks like this:
public class MoreEntites{
public List<MyEntity> MyEntities { get; set; }
}
In the View I want to use MoreEntities to give the user the possibility to enter more datasets than one in just one view (my suggestions which doesnt work of course)
#model myproject.ViewModels.MoreEntities
...
<div class="editor-label">
#Html.LabelFor(model => model.MyEntities.ElementAt(0).MyAttribute)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MyEntities.ElementAt(0).MyAttribute)
#Html.ValidationMessageFor(model => model.MyEntities.ElementAt(0).MyAttribute)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MyEntities.ElementAt(1).MyAttribute)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MyEntities.ElementAt(1).MyAttribute)
#Html.ValidationMessageFor(model => model.MyEntities.ElementAt(1).MyAttribute)
</div>
...
Now in the controller I want to iterate over the list and write every item of MyEntities in the database. When I run the programm I get an exception that my List is null and I should check it for null before I use it.
Is this possible and how does it work? One "Solution" would be to create an Array but in this case my program would be scalable.
Thanks for help!
Works with Array[] of Entity!!!!
Solution:
Model:
public class MyEntity{
public string MyAttribute { get; set; }
}
ViewModel:
public class MoreEntites{
public MyEntity[] MyEntities { get; set; }
}
View:
#model myproject.ViewModels.MoreEntities
...
<div class="editor-label">
#Html.LabelFor(model => model.MyEntities[0].MyAttribute)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MyEntities.[0].MyAttribute)
#Html.ValidationMessageFor(model => model.MyEntities[0].MyAttribute)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MyEntities[1].MyAttribute)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MyEntities[1].MyAttribute)
#Html.ValidationMessageFor(model => model.MyEntities[1].MyAttribute)
</div>
...
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMoreEntitiesAtOnce(MoreEntities set)
{
foreach(var item in set.MyEntities)
{
db.MyEntity.Add(item);
}
db.SaveChanges();
return RedirectToAction("Index");
}
in my case if have to try if its possible to add more TextBoxes to the View by JavaScript
Therefore you need to increment the name of the textboxes in plain html when adding them to the DOM

Fill in form based on dropdown selection (MVC 4)

I am using asp.net mvc 4
Is there a way to update the form based on selection made by the user?
(in this case I want to fill in address fields if something is picked from the dropdown list, otherwise a new address would need to be typed in)
My model:
public class NewCompanyModel
{
[Required]
public string CompanyName { get; set; }
public bool IsSameDayRequired { get; set; }
public int AddressID { get; set; }
public Address RegisterOfficeAddress { get; set; }
}
View:
#model ViewModels.NewCompanyModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { name = "frm", id = "frm" }))
{
#Html.ValidationSummary(true)
<fieldset id="test">
<legend>Company</legend>
<h2>Register office address</h2>
<div class="editor-label">
#Html.LabelFor(model => model.AddressID)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.AddressID, (IList<SelectListItem>)ViewBag.Addresses, new {id = "address", onchange = "window.location.href='/wizard/Address?value=' + this.value;" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
#Html.ValidationMessageFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.RegisterOfficeAddress.StreetName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RegisterOfficeAddress.StreetName)
#Html.ValidationMessageFor(model => model.RegisterOfficeAddress.StreetName)
</div>
and controller:
public ActionResult Address(string value)
{
//get the address from db and somehow update the view
}
The question is how do you update the 'model.RegisterOfficeAddress.StreetName' etc
Just to make clear this is just part of the form so I cannot submit it just yet.
Many thanks
Thanks for your help; I have decided to take a different approach:
On dropdown change I submit the form:
<div class="editor-label">
#Html.LabelFor(model => model.ServiceAddress.AddressID)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ServiceAddress.AddressID, (IEnumerable<SelectListItem>)ViewBag.Addresses, new { onchange = "this.form.submit();" })
#Html.ValidationMessageFor(model => model.ServiceAddress.AddressID)
</div>
and then in controller:
[HttpPost]
public ActionResult NewDirector(NewDirectorVM vm, string value)
{
ModelState.Clear();
if (vm.ServiceAddress.AddressID > 0)
{
//Updates the properties of the viewModel
vm.ServiceAddress = _Repository.GetAddress(vm.ServiceAddress.AddressID);
}
return View("NewDirector", vm);
}
Please notice ModelState.Clear(); which actually allows the view to be updated from the controller (otherwise all the changes made the the viewModel by the controller would have been overwritten by the values in the view).
Common way in such cases is to update other fields via javascript:
$('##Html.IdFor(model => model.AddressID)').on('change',function(){
$.get(...,function(data){
$('##Html.IdFor(model => model.RegisterOfficeAddress.BuildingNameOrNumber)').val(data)
})
})

Add Category Dynamically ASP.Net 4 MVC3 C#

I am working on creating a blog with ASP.Net 4, MVC 3, Razor and C#.
There are 2 seperate tables. 1 for the actual blog post and a relationship table for categories.
The categories displays as a dropdown.
I want to add the ability to add a new category using Ajax so the user does not lose what they have already entered into the form.
What would be the best way to accomplish this?
Here is what I have right now.
Controller Code
public ActionResult Create()
{
ViewBag.category_id = new SelectList(_db.Categories, "id", "category_name");
return View();
}
Razor View
#model NPP.Models.News
#{
ViewBag.Title = "Create News Item";
}
<h2>Create News Item</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>News</legend>
<div class="editor-label">
#Html.LabelFor(model => model.news_title, "Title")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.news_title)
#Html.ValidationMessageFor(model => model.news_title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.news_content, "Content")
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.news_content)
#Html.ValidationMessageFor(model => model.news_content)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.news_teaser, "Teaser (optional)")
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.news_teaser)
#Html.ValidationMessageFor(model => model.news_teaser)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.category_id, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("category_id", String.Empty)
#Html.ValidationMessageFor(model => model.category_id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Thanks for any help in advance. My layout page includes jquery which I would prefer to use.
Add another controler method to return you a list of categories, something like:
public JsonResult Categories()
{
return Json(DB.GetCategorys(), JsonRequestBehavior.AllowGet);
}
Then on the client side, use ajax to get your categories and bind them to your drop down, something like:
$.ajax({
url: 'http://myserver/myapp/mycontroller/Categories',
success: function(data) {
$('#dropCategorys').html('');
$.each(data, function(i, e) {
$('#dropCategorys').append('<option value="' +
e.category_id + '">' + e.category_name + '</option>');
}
}
});
This won't save your current selected item, but you can always check that before clearing the list, and reset it afterwards.
Creating the Category separately via AJAX is not your only option. You could then have a view model like this:
public class CategoryViewModel
{
public string name { get; set; }
public int id { get; set; }
}
public class CreateNewsViewModel
{
public string news_title { get; set; }
public string news_content { get; set; }
public string news_teaser { get; set; }
public string CategoryViewModel category { get; set; }
}
Change your view at the category field:
<div class="editor-label">
#Html.LabelFor(model => model.category, "Category")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.category.id, ViewBag.category_id)
#Html.EditorFor(model => model.category.name) <!-- only show when creating a new category -->
#Html.ValidationMessageFor(model => model.category)
</div>
Then your action would look something like this:
[HttpPost, ActionName("Create")]
public ActionResult DoCreate(CreateNewsViewModel model)
{
if (ModelState.IsValid)
{
if (model.category.id == 0)
{
// create your new category using model.category.name
}
// create an entity from the model and save to your database
return RedirectToAction("Index", "News"); // do whatever you wish when you're done
}
return View("Create", model); // show Create view again if validation failed
}
This is more or less off the top of my head so let me know if I bollocks'ed any parts up.

#Html.EditorFor (Image)

I am trying to allow a user to upload an image to our website and I'm not quite sure about how to use this. I have tried to use multiple types to define the image, including System.Drawing.Image and HttpPostedFileWrapper but the #Html.EditorFor always (understandably) brings up its attributes as fields to edit.
In my view I did have, instead of #Html.EditorFor I did have <input type="file" name="imageToUpload" /> but it didn't get taken through to my view as part of the Model? I am quite new to MVC so I am hoping it is something trivial.
Here is my View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>New Image</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
<input type="file" name="imageToUpload" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
My Controller:
[HttpPost]
public ActionResult CreateImage(string brand, string collection, ImageEditViewModel imageEditViewModel)
{
string fileName = Guid.NewGuid().ToString();
string serverPath = Server.MapPath("~");
string imagesPath = serverPath + String.Format("Content\\{0}\\Images\\", Helper.Helper.ResolveBrand());
string newLocation = Helper.Helper.SaveImage(fileName, imagesPath, imageEditViewModel.Image.InputStream)
Image image = new Image
{
Collection = ds.Single<Collection>(c => c.Season == collection
&& c.Brand.Name == brand),
Description = imageEditViewModel.Description,
Location = "newLocation",
Order = Helper.Helper.GetImageOrder(brand, collection)
};
ds.InsertOnSubmit<Image>(image);
ds.SubmitChanges();
return RedirectToAction("Brand");
}
And finally the ViewModel:
public class ImageEditViewModel
{
public int CollectionId { get; set; }
public string Description { get; set; }
public HttpPostedFileWrapper Image { get; set; }
public int Order { get; set; }
}
Ensure to specify the correct enctype="multipart/form-data" on your form or you won't be able to upload files:
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>New Image</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ImageToUpload)
</div>
<div class="editor-field">
<input type="file" name="imageToUpload" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
And if you wanted to use an EditorFor helper to generate the file input you could use the following:
<div class="editor-label">
#Html.LabelFor(model => model.ImageToUpload)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ImageToUpload)
</div>
and then define a custom editor template for the HttpPostedFileBase type (see below that you need to modify your model to use this type actually). So the editor template in ~/Views/Shared/EditorTemplates/HttpPostedFileBase.cshtml:
#model HttpPostedFileBase
#Html.TextBox("", null, new { type = "file" })
and on your view model use the HttpPostedFileBase type and make sure that the name of the property matches the name of the file input on your form:
public class ImageEditViewModel
{
public int CollectionId { get; set; }
public string Description { get; set; }
public HttpPostedFileBase ImageToUpload { get; set; }
public int Order { get; set; }
}
Also make sure to checkout the following blog post.

Categories