Pass data to partial class - asp.net-mvc

I am trying to pass a model to my partial class in asp.net however it keeps giving me the following error:
I tried calling the partial class the following ways:
<section id="categoryPartial">
#*1*# #Html.Partial("_CategoryPartial", new EindopdrServer.Models.Category())
#*2*# #Html.Partial("_CategoryPartial", new EindopdrServer.Models.Category{ Name => Model.Name })
#*3*# #Html.RenderPartial("_CategoryPartial", new EindopdrServer.Models.Category { Name => Model.Name })
</section>
My partial class:
#model IEnumerable<EindopdrServer.Models.Category>
<table>
<tr>
#if(Model != null){
#foreach (var item in Model) {
<td class="categoryPartial">
<b>#Html.DisplayFor(modelItem => item.Name)</b>
</td>
}
}
</tr>
</table>
Any solutions?
After removing the # and if statement:

Because the if-statement is code, and not markup, the foreach is already considered code. You don't need to have # before it.
So, simply remove the # character before the foreach

Related

Model retains it's value after Submit to server

I'm facing this weird problem ,unable to make sense of it,I have a form which accepts Person Id and then reads the data from an API and fills the UI for person Edit purposes.
Here is the markup of this form,I'm guessing its has something to do with Model binding as I have two Form tag and both having the same Model Id.
#using (Html.BeginForm("UpdatePerson", "Person", FormMethod.Get))
{
<table>
<tr>
<td colspan="2">
<h3>Read Person for Edit</h3>
</td>
</tr>
<tr>
<td>
<label>#Html.LabelFor(m => m.Id)</label>
</td>
<td>
#Html.TextBoxFor(m => m.Id)
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="btnReadPerson" value="Read Person" />
</td>
</tr>
</table>
}
#using (Html.BeginForm("UpdatePerson", "Person", FormMethod.Post))
{
<table>
<tr>
<td>
<label>#Html.LabelFor(m => m.Id)</label>
</td>
<td>
#Html.TextBoxFor(m => m.Id, new { #readonly = "readonly" })
</td>
</tr>
<tr>
<td>
<label>#Html.LabelFor(m => m.Type)</label>
</td>
<td>
#Html.TextBoxFor(m => m.Type)
</td>
</tr>
I have stripped the view,I tried to kept it brief.
Below is the Action which handles the Get
[HttpGet]
[ActionName("UpdatePerson")]
public ActionResult UpdatePersonRead(PersonEditModel model)
{
if (model.Id.HasValue)
{
var apiClient = new ApiClient (ApiVersions.v1);
var segmentReplaceList = new Dictionary<string, string> { { "{id}", model.Id.Value.ToString() } };
bool ApiHitStatus = false;
var result = apiClient.MakeAPIRequest(out ApiHitStatus, ResourceUriKey.Person, segmentReplaceList, HttpVerbs.Get, string.Empty);
model = new PersonEditModel();
if (ApiHitStatus)
{
var personToBeUpdated = JsonConvert.DeserializeObject<RootChildPerson>(result);
if (personToBeUpdated != null)//Assigning json obj to model
{
model.NameFirst = personToBeUpdated.name_first;
model.NameLast = personToBeUpdated.name_last;
model.NameMiddle = personToBeUpdated.name_middle;
model.SocialSecurityNumber = personToBeUpdated.social_security_number;
model.SubType = PersonHelper.SubTypeValue(personToBeUpdated.sub_type);
model.Type = "person";
model.DateOfBirth = personToBeUpdated.date_of_birth;
model.Id = personToBeUpdated.id;
}
}
}
return View(model);
}
Now since the Person Id 4 does not corresponds to any person ,so I receive Null json object which upon conversion to C# class results in an empty (not null because it has every property set to null or empty) personToBeUpdated object which is then assigned to the model,I have checked model.Id becomes null in the Controller and even in the View ,but somehow it assigns input value that is 4 (it was null) to both Person Id textboxes.
Kindly let me know whats happening here.
Well as commented by #StephenMuecke ,So I cleared model before updating it.
model = new PersonEditModel();
ModelState.Clear();
Its also interesting to note that view takes data from ModelState instead of current specified model,
HtmlHelpers controls (like .TextBoxFor() etc.) don't bind to model values on Postback, but rather get their value directly out of the POST buffer from ModelState.
Taken from ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes

Why is DisplayForModel not showing the expected output?

I have a simple razor page, where the first part correctly shows information from each element in my model in a table. After that I'm trying to use DisplayFor to show me every property in the model, but it generates 123 for each iteration. What am I doing wrong?
#model System.Data.Entity.IDbSet<DBFramework.MyPerson>
#{
ViewBag.Title = "Home Page";
}
<p></p>
<table border="1">
<thead>
<tr>
<th style="width:300px;">Name</th>
<th style="width:300px;">Age</th>
</tr>
</thead>
#foreach (var p in Model)
{
<tr>
<td>#Html.Label(p.Name)</td>
<td>#Html.Label(p.Age.ToString())</td>
</tr>
}
</table>
#foreach (DBFramework.MyPerson x in Model)
{
#Html.DisplayForModel(x)<br/>
}
Creates the following output:
Name Age
Mike 40
Penny 1
Kunal 30
123
123
123
Try this:
#foreach (var item in Model)
{
#Html.DisplayFor(model => item)
}
DisplayFor and DisplayForModel are used with templates in Views\Shared\DisplayTemplates.
When you call DisplayForModel, it will take the page model (Model) and if you specify a parameter, will try to load the template with the name provided (if string) or add the object as additional data in ViewData. When you called:
#foreach (DBFramework.MyPerson x in Model)
{
#Html.DisplayForModel(x)<br/>
}
You told it - Display Model which is type System.Data.Entity.IDbSet<DBFramework.MyPerson> and add MyPerson in the template ViewData. Do this 3 times. You also didn't give him a hint to select a DisplayTemplate and it will try to use convention to find it.
As Bappi Datta said, if you want to display a template for MyPerson, you need to call:
#foreach (var item in Model)
{
#Html.DisplayFor(model => item)
}
However, you need a MyPerson display template created which accepts #model DBFramework.MyPerson to render the item or it will simply do a .ToString() by default I believe.

Get model from partial view to controller

Is it possible to pass model to controller with #Html.Partial?
Using plain <td> in view return list of rows, while this exact same <td> wrapped in partial returns null on form submit
#using ( Html.BeginForm() )
{
<table>
<tr>
<th></th>
</tr>
<tr>
#for ( int i = 0; i < Model.Rows.Count; i++ )
{
#*<td class="row">Book #Html.DisplayFor(x => Model.Rows[i].RowNum) #Html.DropDownListFor(x => Model.Rows[i].Selected, Model.Rows[i].Data) </td>*#
#Html.Partial("Row", Model.Rows[i])
}
</tr>
</table>
<input type="submit" value="Submit" />
}
Html.Partial renders a partial view.
If your view is already expecting a model of that type, you can pass it along.
#Html.Partial("ViewName", Model)
To send values to an action of a controller, you can try using Html.Action
#Html.Action("actionName","ControllerName", new {RowNum = Model.Row[i].RowNum})
You can pass values using the anonymous object
You probably want to use the RenderPartial Extension, it should give you what you need.

Passing value from EditorFor to controller

This is my view where education is the list in the model.
#using chpayroll.Models.CustInformations
#model CustInfoExtract
#Html.HiddenFor(x => x.flag, new { #id = "flag" })
#Html.HiddenFor(x => x.StaffId)
<table style=" width:730px">
<tr>
<th>Country</th>
<th>Board</th>
<th>Level</th>
<th>PassedYear</th>
<th>Division</th>
</tr>
<tr>
#Html.EditorFor(x => x.education)
</tr>
<tr>
<td><input type="submit" value="Add Another" id="addedu"/> </td>
</tr>
</table>
I have editor template as below
#using staffInfoDetails.Models
#model staffInfo.education
#Html.HiddenFor(x=>x.staffId)
<tr>
<td >#Html.DropDownListFor(x => x.country, Model.countryList, "--select--", new { #id="country"})</td>
<td>#Html.TextBoxFor(x => x.board, new { #id="board"})</td>
<td>#Html.TextBoxFor(x => x.level, new { #id="level"})</td>
<td>#Html.TextBoxFor(x => x.passedYr, new { #id="passedYr"})</td>
<td>#Html.DropDownListFor(x => x.passedDiv, Model.passedDivList, "--select--", new { #id="division"})</td>
</tr>
I am trying to pass model from controller to view and back from view to controller. While I was passing model to view, the education list passed, but, when i tried to pass model from view to controller, everything else passed except for the education list. How can I solve this problem ?
Only the selected value from the drop down list will be posted back so you'll need to re-populate your drop down list if validation fails (ie. if the View has to be re-displayed).
Your POST action might look something along the lines of the following:
[HttpPost]
public ActionResult Home(CustInformations viewModel)
{
if (!ModelState.IsValid)
{
// Re-populate drop-down list and redisplay form
viewModel.DropdownListOptions = _repository.getEductionList();
return View(viewModel);
}
// Validation passed
// Save, update, etc and redirect to new page
}

ASP.NET MVC FormCollection TextArea

I have a textarea that represents a description field. The descriptions have commas so when trying to split the field's descriptions the data is not parsed correctly. How can I get each row's description correctly.
var DescList = FormValues["Item.Description"].Split(',').Select(item => item).ToList<string>();
//will not work for obvious reasons. Comma delimited FormCollection has commas to identify separate row data.
It seems like Microsoft designed the FormsCollection without the textarea control in mind. A text area with commas will not work when trying to access each value. What is interesting is that the _entriestables property has it in the perfect format but they chose to make it a private property. Very frustrating.
`
Here is the important part of my viewmodel.
public class TenantViewModel
{
public Tenant Tenant { get; set; }
public Site Site { get; set; }
}
My view is populated like this:
if (Model != null && Model.Tenant != null && Model.Tenant.Site != null && Model.Tenant.Site.Count() > 0)
{<div class="detailsbox_view">
<table id="tblTenantSites">
<tr>
<th>#Html.LabelFor(item => item.Site.Title)</th>
<th>#Html.LabelFor(item => item.Site.Description)</th>
</tr>
#foreach (var Item in Model.Tenant.Sites)
{
<tr>
#Html.HiddenFor(modelItem => Item.SiteId)
<td>
#Html.EditorFor(modelItem => Item.Title)
</td>
<td>
#Html.TextAreaFor(modelItem => Item.Description, new {#width="400" })
</td>
</tr> }
</table>
As you see this site table is a child of Tenant object. This child record does not get automatically updated using this method but the Tenant data does automatically get updated. This is the reason I tried the FormColelction instead.
Is there something I am missing to make this work?
try with this useful function
ValueProviderResult Match=FormCollection.GetValue("ValueProvider");
When you have multiple fields with the same name attribute, they'll come back into your FormCollection as an array. So upon posting a view like this:
<form action="/Home/MyAction">
<textarea id="row_one_description" name="description">
First row's description
</textarea>
<textarea id="row_two_description" name="description">
Second row's description
</textarea>
<input type="submit" value="Submit" />
</form>
you could do something like this in your action
[HttpPost]
public ActionResult MyAction(FormCollection collection)
{
var descriptionArray = collection["description"];
string firstRowDescription = descriptionArray[0];
string secondRowDescription = descriptionArray[1];
}
I must note that this is not the recommended way of dealing with posted data. You should instead be building your view using data from a view model and using strongly typed html helpers to render your controls. That way when you post, your action can take the ViewModel as a parameter. Its properties will be automatically bound and you will have a nice object to play with.
[HttpPost]
public ActionResult MyAction(MyViewModel viewModel)
{
foreach (var row in viewModel.Rows)
{
string description = row.Description;
}
}
EDIT
I'm still assuming a lot about your ViewModel but perhaps try this:
<table id="tblTenantSites">
<tr>
<th>#Html.LabelFor(model => model.Site.Title)</th>
<th>#Html.LabelFor(model => model.Site.Description)</th>
</tr>
#for (var i = i < Model.Tenants.Sites.Count(); i++) {
<tr>
#Html.HiddenFor(model => model.Tenants.Sites[i].SiteId)
<td>
#Html.EditorFor(model => model.Tenants.Sites[i].Title)
</td>
<td>
#Html.TextAreaFor(model => model.Tenants.Sites[i].Description, new { #width="400" } )
</td>
</tr>
}
</table>
You could also try ,
string Match=FormCollection.GetValue("ValueProvider").AttemptedValue;

Resources