I am trying to display like this
var value = "Kartheek#gmail.com"
#Html.DisplayName(value)
Result is : com only.
why? what have to use in this case
here i am explaining more
My intention is to display content in very generic with grid.
public class Grid
{
private Type type { get; set; }
public Grid(IEnumerable datasource)
{
if (datasource == null)
{
throw new ArgumentNullException("datasource");
}
this.type = datasource.GetType().GetGenericArguments().Single();
this.Data = datasource;
}
public IEnumerable Data { get; set; }
public IEnumerable<System.Reflection.PropertyInfo> Props
{
get
{
return this.type.GetProperties().AsEnumerable();
}
}
}
This is my c# class for grid. i am assigning values in to Grid.data and with viewbag i am sending grid data to view and then i am using this with in partial view
here my partial view code
#if (Model != null)
{
<table style="width: 100%">
<thead>
<tr>
#foreach (var col in Model.Props)
{
<th>#Html.Label(col.Name)</th>
}
</tr>
</thead>
<tbody>
#foreach (var item in Model.Data)
{
<tr>
#foreach (var prop in Model.Props)
{
var val = prop.GetValue(item, null).ToString();
<td>#Html.DisplayName(val)</td>
}
</tr>
}
</tbody>
</table>
}
Finally i got answer with this.. But i am not satisfied with that bcz there is another good solution for it.
var val = "kartheek#gmail.com";
<span>#val</span>
Related
I want to download the file that I uploaded in the database. The file stored in the byte array. I have created the getDataStudent function and it is working well.
My controller is below.
public class Student: Controller
{
private StudentViewModel getDataStudent(StudentViewModel model)
{
var students = db.students.ToList();
var documents = documentRepo.GetList_Documents();
var queryJoin1 =
from student in students
from document in documents.Where(w => student .UniqueNumber == w.UniqueNumber).DefaultIfEmpty()
select new StudentDto
{
ID = student.ID,
Name = student.Name,
File = document?.DetailFile ?? null, //file to download
};
IEnumerable <StudentDto> studentss= null;
studentss = queryJoin1;
return studentss;
}
public ActionResult Index(StudentViewModel model)
{
studentViewModel = getDataStudent(model);
return View(studentViewModel );
}
[HttpPost]
public FileResult DownloadFile()
{
//code
}
}
and my view is below
#model Student.Data.ViewModels.StudentViewModel
#using (Html.BeginForm())
{
<table class="table">
<tr>
<th>Name</th>
<th>File</th>
</tr>
#foreach (Student.Data.ViewModels.StudentViewModel item in Model)
{
<tr>
<td>#Html.DisplayFor(modelitem => item.Name)</td>
<td> #Html.DisplayFor(modelitem => item.File)</td>
</tr>
}
</table>
}
File Result is still empty, I confused using FileResult.
can you guys tell me how to download files using FileResult on the controller, using the getDataStudent function that I created.
I have never made a file download function before. please help:)
You can implement like this:
public FileStreamResult DownloadFile()
{
// get your students here
var students = ...
string name = "yourname.txt";
FileInfo info = new FileInfo(name);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
foreach(var item in students){
writer.WriteLine("{0} {1}", item.ID, item.Name);
}
}
}
return File(info.OpenRead(), "text/plain");
}
I am new to MVC and now stuck in a serious problem. it is for me, very serious
I need to load a view with a list of meetings (which is loading fine) in html , I have added a checkbox to each row also. Now I need to save to the database ,only the checked values. But the controller is returning null when posting.. Really stuck and cant find a solution.
Pls see code below which I have done
Model
public class aMeet
{
public List<AcceptedRecords> amList { get; set; }
public static List<AcceptedRecords> GetamList()
{
DataSet ds = new DataSet();
List<AcceptedRecords> resultlist = new List<AcceptedRecords>();
using (cmd)
{
cmd.CommandText = #"SELECT Line_code,person_code,person_address from tbl where meeting_code =859489;
ds = cmd.ExecuteDataSet();
}
if (!Utils.IsDataSetEmpty(ds))
{
AcceptedRecords tpmApp;
foreach (DataRow row in ds.Tables[0].Rows)
{
tpmApp = new AcceptedRecords();
tpmApp = tpmApp.LoadRecords(row);
resultlist.Add(tpmApp);
}
}
return resultlist;
}
}
Model
public class AcceptedRecords
{
public int line_Code { get; set; }
public string person_Name { get; set; }
public string person_Address { get; set; }
public bool extra_checked { get; set; }
}
View
#model projct.Models.aRecs
#using (Html.BeginForm("AddRecord","Home"))
{
<table id="tbl" style ="width:100%" cellpadding="0" cellspacing="0" class="race-fields">
<thead>
<tr>
<th style="width:500px">line code</th>
<th style="width:100px">name</th>
<th style="width:500px">address</th>
<th style="width:500px">extra</th>
</tr>
</thead>
<tbody>
<tr>
#for (int i = 0; i < Model.amList.Count; i++)
{
<tr class="EvenRow">
<td>
#Html.DisplayFor(m => m.amList[i].line_Code) </td>
<td>#Html.DisplayFor(m => m.amList[i].person_name) </td>
<td>#Html.DisplayFor(m => m.amList[i].person_address) </td>
<td>
#Html.CheckBoxFor(m => m.amList[i].extra_checked) </td>
</tr>
}
</tr>
<tr>
<span>
<input type="submit" Value ="Save"/>
</span>
</tr>
</tbody>
</table>
}
Controller
[HttpPost]
public ActionResult AddRecord(List<aMeet> spm)
{
if (spm == null)
throw new ApplicationException("No Parameters passed to Create");
int? appID = 0;
return Json(appID);
}
}
--- It Is triggering to controller on Save but model [spm] is null.
How to get this corrected. Here I need to save to database the tr elements that are checked. Please request any help. I have tried a lot of things but the model is always null/
Many thanks
Assuming your aRecs class has a amList property which is a list of AcceptedRecords
public class aRecs
{
public List<AcceptedRecords> amList { set; get; }
}
Assuming line_code value is a unique (may be primary key) to get a record from your corresponding table, In your view, you need to keep the line_code property value of each item in amList in a hidden field so that when the form is submitted you will get this value and using that you can query the corresponding record and update it.
#model YourNamespaceHere.aRecs
#using (Html.BeginForm("AddRecord","Home"))
{
<table>
#for (int i = 0; i < Model.amList.Count; i++)
{
<tr class="EvenRow">
<td>
#Html.DisplayFor(m => m.amList[i].line_Code)
</td>
<td>#Html.DisplayFor(m => m.amList[i].person_Name) </td>
<td>
#Html.CheckBoxFor(m=>m.amList[i].extra_checked)
#Html.HiddenFor(m => m.amList[i].line_Code)
</td>
</tr>
}
</table>
<input type="submit"/>
}
And in your HttpPost action, your parameter will be a single object of aRecs
[HttpPost]
public ActionResult AddRecord(aRecs model)
{
foreach (var item in model.amList)
{
var lineCode = item.line_Code;
var isChecked = item.extra_checked;
/// get the record using lineCode and update the record.
}
return RedirectToAction("Index");
}
Hi thank you all for assisting me. I am very new to ASP.net MVC and EF and am playing around to do some real project. I would really appreciate if someone could please guide me of how I can insert data into two tables in SQL with one to many relationships.
I have a requirement where I need to add multiple families to one behavior case.
tblCase [case_id] [case_no]
tblFamily [family_id] [first_name] [last_name] [case_id]
After following an online tutorial I am able to add multiple families but I can not get my head around how to:
Add a new case -> retrieve the last inserted case_id
Add all the families with the last inserted case_id in one submit button click.
My view looks like the following:
#model List<TestMVC.Family>
#{
ViewBag.Title = "BulkData";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<style>
td {
padding: 5px;
}
</style>
<div style="width:700px; padding:5px; background-color:white;">
#using (Html.BeginForm("BulkData", "Save", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
if (ViewBag.Message != null)
{
<div style="border:solid 1px green">
#ViewBag.Message
</div>
}
<div id="dvCase">
<table>
<tr>
<td>Case Name</td>
<td><input type="text" value="" /></td>
</tr>
<tr>
<td>Case No</td>
<td><input type="text" value="" /></td>
</tr>
</table>
</div>
<div>Add New</div>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Case Id</th>
<th></th>
</tr>
#if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr style="border:1px solid black">
<td>#Html.TextBoxFor(a => a[j].firstName)</td>
<td>#Html.TextBoxFor(a => a[j].lastName)</td>
<td>#Html.TextBoxFor(a => a[j].case_id)</td>
<td>
#if (j > 0)
{
Remove
}
</td>
</tr>
j++;
}
}
</table>
<input type="submit" value="Save" />
}
</div>
and my controller looks like :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TestMVC.Controllers
{
public class SaveController : Controller
{
//
// GET: /Save/
public ActionResult BulkData()
{
Case bc = new Case {case_id=0,case_no=""};
// This is only for show by default one row for insert data to the database
List<Family> ci = new List<Family> { new Family { family_id = 0, firstName = "", lastName = "", case_id= 0 } };
return View(ci);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult BulkData(List<Family> ci)
{
if (ModelState.IsValid)
{
using (FamilyContext dc = new FamilyContext())
{
var behaveCase = new Case();
behaveCase.case_no = "1234";
dc.Cases.add(behaveCase);
foreach (var i in ci)
{
i.Case = behaveCase;
dc.Families.Add(i);
}
dc.SaveChanges();
ViewBag.Message = "Data successfully saved!";
ModelState.Clear();
ci = new List<Family> { new Family { family_id = 0, firstName = "", lastName = "", case_id = 0 } };
}
}
return View(ci);
}
}
}
and my model definitions
namespace TestMVC
{
using System;
using System.Collections.Generic;
public partial class Case
{
public Case()
{
this.Families = new HashSet<Family>();
}
public int case_id { get; set; }
public string case_no { get; set; }
public virtual ICollection<Family> Families { get; set; }
}
}
namespace TestMVC
{
using System;
using System.Collections.Generic;
public partial class Family
{
public int family_id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public int case_id { get; set; }
public virtual Case Case { get; set; }
}
}
Model which is added that is 'i' over here : dc.Families.Add(i); when dc.SaveChanges() called it will modify 'i' with its primary key as :
if (ModelState.IsValid)
{
using (FamilyContext dc = new FamilyContext())
{
var behaveCase = new Case();
behaveCase.case_no = "1234";
dc.Cases.add(behaveCase);
dc.SaveChanges(); // Save Changes Occurred. primary key in inserted in behaveCase
int pk = behaveCase.case_id; // You can get primary key of your inserted row
foreach (var i in ci)
{
i.Case = behaveCase;
dc.Families.Add(i);
dc.SaveChanges(); // Save Changes Occured. Primary key of i is inserted
int pkFam = i.family_id; // You can get primary key of your inserted row
}
ViewBag.Message = "Data successfully saved!";
ModelState.Clear();
ci = new List<Family> { new Family { family_id = 0, firstName = "", lastName = "", case_id = 0 } };
}
}
I have spent a lot of time on this, but i can't seem to get it to work. I have a legacy web forms app that i am rewriting in MVC. It has all bussiness logic coming from stored procs and in the iterest of time, I decided to reuse the BAL(bussiness layer) and DAL. Here is what I have:
Model
public class GridDisplay
{
public List<string> columnNames { get; set; }
public List<string> fieldValues { get; set; }
}
Controller
public ActionResult PatientInfo()
{
var model = new PatientInfoViewmodel();
ViewBag.countries = model.FillCountryDropDown();
ViewBag.studies = model.FillStudyDropDown();
SearchElements SE = new SearchElements { StudyID = "PRMDEMO" };
List<string> fields = new List<string>();
DataSet ds = new DataSet();
ds = pibl.PopulateData(SE);
var display = new List<GridDisplay>();
display = model.BuildGridData(SE);
ViewBag.columns = display[0].columnNames.ToList();
ViewBag.fields = display;
return View();
}
List of GridDisplays:
public List<GridDisplay> BuildGridData(SearchElements SE) //(string country, string studyID, string patientid, string lastname)
{
DataSet ds = new DataSet();`enter code here`
ds = pibl.PopulateData(SE);
GridDisplay display = new GridDisplay();
List<GridDisplay> displayList = new List<GridDisplay>();
string strtemp = string.Empty;
display.columnNames = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
display.columnNames.Add(row["label"].ToString());
}
display.fieldValues = new List<string>();
foreach (DataRow row in ds.Tables[1].Rows)
{
display.fieldValues = new List<string>();
foreach (DataColumn column in ds.Tables[1].Columns)
{
if (column.Caption != "STUDY" & column.Caption != "PATIENT_ID")
{
display.fieldValues.Add(row[column].ToString());
}
if (column.Caption == "PATIENT_ID")
{
strtemp = row[column].ToString();
}
}
display.fieldValues.Add(strtemp);
displayList.Add(new GridDisplay() { columnNames = display.columnNames, fieldValues = display.fieldValues});
}
return displayList;
}
The displayList has everything I need and I am able to display the columns, but not the fields. Below is the view portion that pertains to this(one of my versions)
<div id="dvDynamicPatient" style="overflow: auto;">
<table id="gvDynamicPatient">
<tr>
#foreach (var col in #ViewBag.columns)
{
<th id="gridHeader" style=" white-space: nowrap;">
#col
</th>
}
</tr>
<tr>
#foreach (var item in #ViewBag.fields.fieldvalues)
{
<td id="gridCell" style="border-style: solid; color: #000000; white-space: nowrap">
#item
</td>
}
</tr>
</table>
</div
Understanding models is a beautiful thing. I did figure this out. To recap, I have a stored procedure that returns two result sets via a dataset. Dataset.Tables[0] has header strings and Dataset.Tables[1] contains the information to be displayed.My task was to create an MVC 4 application to view this and then some.
Model
public class GridDisplay
{
public List<string> columnNames { get; set; }
public List<List<string>> fieldValues { get; set; }
}
Controller
public ActionResult PatientInfo()
{
var model = new PatientInfoViewmodel();
// build dropdown lists
ViewBag.countries = model.FillCountryDropDown();
ViewBag.studies = model.FillStudyDropDown();
SearchElements SE = new SearchElements { StudyID = "PRMDEMO" };
DataSet ds = new DataSet();
ds = pibl.PopulateData(SE);
var gridDisplay = new GridDisplay();
gridDisplay = model.BuildGridData(SE);
return View(gridDisplay);
}
View
<div id="dvDynamicPatient" style="overflow: auto;">
<table id="gvDynamicPatient">
<tr>
#foreach (var col in Model.columnNames)
{
<th id="gridHeader" style="white-space: nowrap;">
#col
</th>
}
</tr>
#for (int i = 0; i < Model.fieldValues.Count; ++i)
{
<tr id="row" style="white-space: nowrap;">
#foreach (var item in Model.fieldValues[i])
{
<td id="col" style="white-space: nowrap;">
#item
</td>
}
</tr>
}
</table>
</div>
I have a simple shopping cart model which contains a list of items:
public class ShoppingCart
{
public List<Item> Items { get; set; }
public double Tax { get; set; }
// ... some other properties
}
public class Item
{
public string Name { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
public double TotalCost { get { return Quantity * Price; } }
}
I want to modify the quantity of a particular item and I've made the following View:
<%using (Html.BeginForm("Recalculate", "ShoppingCart", Model))
{ %>
<table id="cartTable" border ="5px" cellpadding="5px" cellspacing="5px" width="640">
<tr>
<td><b>Item Name</b></td>
<td><b>Item Qty</b></td>
<td><b>Item Price</b></td>
<td><b>Subtotal</b></td>
</tr>
<%
if (Model != null && Model.Items != null)
{
foreach (ShoppingCart.Models.Item item in Model.Items)
{
%>
<tr>
<td><%: item.Name%></td>
<td><%: Html.TextBoxFor(m => m.Items[Model.Items.IndexOf(item)], new { #Value = item.Quantity })%></td>
<td><%: String.Format("{0:C}", item.Price)%></td>
<td><%: String.Format("{0:C}", item.TotalCost)%></td>
</tr>
<%
}
}
%>
<!-- some other rows/columns go here -->
</table>
<input type="submit" value="Update Cart" />
<%} %>
And my controller:
public class ShoppingCartController : Controller
{
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Show(ShoppingCart model)
{
if (model!= null && model.Items == null)
{
List<Item> items = new List<Item>();
items.Add(new Item { Name = "Hat", Price = 20.0, Quantity = 1 });
items.Add(new Item { Name = "Snowboard", Price = 430.0, Quantity = 1 });
items.Add(new Item { Name = "Goggles", Price = 24.0, Quantity = 3 });
model.Items = items;
model.Tax = 6.5;
}
return View(model);
}
[HttpPost]
public ActionResult Recalculate(ShoppingCart model)
{
if (model != null && model.Items!=null)
{
foreach (Item item in model.Items)
{
if (item.Quantity == 0)
{
model.Items.Remove(item);
}
else if (item.Quantity < 0)
{
ModelState.AddModelError("error", "The quantity for " + item.Name + " must not be smaller than 0.");
}
}
}
return RedirectToAction("Show", "ShoppingCart", model);
}
}
Unfortunately when I click on the Update Cart button it calls my Recalculate function, but now all of the items in the Items list are null. How can I keep the items AND update the quantity of a given item?
In the BeginForm function I tried passing in the current model and not passing it a model at all... nothing changes. Could anybody help me figure this out?
Do these changes in appropriate locations and things would start working. Note that while the postback the Price and TotalCost would not be populated in the model as the corresponding rendered items are static text. These can be repopulated in the Controller or add hidden field in the view so that these can be posted and repopulated.
<%using (Html.BeginForm("Recalculate", "ShoppingCart", FormMethod.Post))
<td><%: Html.TextBoxFor(m => m.Items[Model.Items.IndexOf(item)].Quantity)%></td>
//return RedirectToAction("Show", "ShoppingCart", model);
return View("Show", model);
<%= Html.TextBox("Quantity", Model.Items[Model.Items.IndexOf(item)].Quantity ) %>
This is a nice blog post, worth a read: http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx