How can I model bind to a textbox placeholder? - asp.net-mvc

I have been able to bind the info to the textbox like so:
<div id="wordsInsideOfText">
#foreach (var item in Model.KVpairs)
{
#Html.TextBoxFor(modelItem => item)
<hr />
}
</div>
but what I am trying to do is something like this:
<div id="wordsInsideOfText">
#foreach (var item in Model.KVpairs)
{
#Html.TextBoxFor().PlaceHolder(modelItem => item)
<hr />
}
</div>
So that I can get the information from my model into the placeholder rather than as regular text.I have looked around some, and maybe I don't fully understand how to phrase my question/search but I wasn't able to come up with anything.

you have to do like this:
#Html.TextBoxFor(modelItem => item, new {placeholder = item})
or:
<input type="text" placeholder="#item"/>

Related

MVC foreach set item.ID to model.ID

I have a form that shows all the available hotel rooms, each room has a button that does a HttpPost if clicked, I have made a property in the BookingViewModel called 'RoomID'. I would like to assign the item.RoomID to Model.RoomID so I can use it in my controller to get the id from the selected room but i'm not sure how to achieve this.
ChooseRoom View
#foreach (var item in Model.AvailableRooms)
{
<li class="room-item clearfix">
<h5>#item.Name</h5>
<div class="room-list-left">
<img src="#item.Image" alt="" />
</div>
<div class="room-list-right">
<div class="room-meta">
<ul>
<li><span>Occupancy:</span> #item.Adults Adults #item.Childs Children</li>
#if (item.SmokingRoom)
{
<li><span>Smoking Allowed:</span> Yes</li>
}
else
{
<li><span>Smoking Allowed:</span> No</li>
}
</ul>
</div>
<div class="room-price">
<p class="price">From: <span>$#item.Price</span> / Night</p>
</div>
<div class="clearboth"></div>
#using (Html.BeginForm("chooseroom", "booking", FormMethod.Post))
{
<input class="button2" type="submit" value="Select Room" />
}
BookingController
[HttpPost]
public ActionResult ChooseRoom(BookingViewModel vm)
{
BookingViewModel bookingObj = GetBooking();
bookingObj.SelectedRoom = Repository.GetRoomByID(vm.RoomID);
return View("reservation", bookingObj);
}
Thank you for your time!
update your begin form as below
#using (Html.BeginForm("chooseroom", "booking", FormMethod.Post))
{
<input type="hidden" name="RoomId" value="#item.RoomID" />
<input class="button2" type="submit" value="Select Room" />
}
Just need to provide input tags having the same name as your ViewModel property.
You could add inputs in foreach loop , it should be inside form. Something like this <input name="Model.AvailableRooms[index].RoomID" value="Id Here"/>
Or if you want to select one Room you should use ajax and post id.
If I'm not wrong you form is in loop,so you could add hidden input with id
#Html.HiddenFor(c => c.AvailableRooms[index].RoomID)

Model is null with Html.BeginForm() ASP.NET MVC

I encountered following problem:
user visits site, clicks "Add" and then it's sending back to Controller, Model is retrieved and send to View one more time. Inside view, I check whether Model is not null
and displays data.
#if (Model != null)
{
<div id="appInfo">
<table>
<tr>
<th>#Html.DisplayNameFor(x => Model.tytul)</th>
<th>#Html.DisplayNameFor(x => Model.kategoria.nazwa)</th>
<th>#Html.DisplayNameFor(x => Model.liczba_ocen)</th>
<th>#Html.DisplayNameFor(x => Model.avg_ocena)</th>
<th>#Html.DisplayNameFor(x => Model.typ)</th>
</tr>
<tr>
<td>#Model.tytul</td>
<td>#ViewData["kategoria"]</td>
<td>#Model.liczba_ocen</td>
<td>#Model.avg_ocena</td>
<td>#Model.typ</td>
</tr>
</table>
</div>
<div>
#using (Html.BeginForm("Confirm", "Wydawca", new { app = #Model }))
{
<input type="submit" value="Cofirm it" />
}
</div>
At the end button "Confirm it" is created and once you click it invokes Confirm Method but app variable is always null. If I set its value to anything but Model it works.
[HttpPost]
public ActionResult Confirm(aplikacja app)
{
...
}
While creating button "Confirm it" Model is not null, I checked. Do you happen to know what is going wrong?
Generated html
<form action="/Wydawca/Confirm?app=Adds.Models.aplikacja" method="post">
<input type="submit" value="Zatwierdź" />
The Html.BeginForm should wrap around all of your input elements or it has nothing to post. Change your view to this:
#if (Model != null)
{
#using (Html.BeginForm("Confirm", "Wydawca", new { app = #Model }))
{
<div id="appInfo">
<table>
<tr>
<th>#Html.DisplayNameFor(x => Model.tytul)</th>
<th>#Html.DisplayNameFor(x => Model.kategoria.nazwa)</th>
<th>#Html.DisplayNameFor(x => Model.liczba_ocen)</th>
<th>#Html.DisplayNameFor(x => Model.avg_ocena)</th>
<th>#Html.DisplayNameFor(x => Model.typ)</th>
</tr>
<tr>
<td> #Model.tytul</td>
<td>#ViewData["kategoria"]</td>
<td>#Model.liczba_ocen</td>
<td>#Model.avg_ocena</td>
<td>#Model.typ</td>
</tr>
</table>
</div>
<div>
#Html.HiddenFor(x => Model.tytul)
#Html.HiddenFor(x => Model.kategoria.nazwa)
#Html.HiddenFor(x => Model.liczba_ocen)
#Html.HiddenFor(x => Model.avg_ocena)
#Html.HiddenFor(x => Model.typ)
<input type="submit" value="Cofirm it" />
</div>
}
}
You are attempting to pass an object (#Model) as a route parameter (app). Route parameters should contain scalar values (int, string, etc), not objects. View the generated HTML source in the browser and see what the <form action=""> is being set as. Then review the concept of model binding.

Split in View asp.net mvc4

CONTROLLER:
public ActionResult Index()
{
SonerSevincComEntities context = new SonerSevincComEntities();
var Konular = context.Konu.ToList();
return View(Konular);
}
VİEW:
<div class="primary">
#foreach (var item in Model)
{
<h2>
<a href="Subject?SubjectId=
#Html.DisplayFor(model => item.Id)">
#Html.DisplayFor(model => item.Baslik)</a>
</h2>
<p class="post-info">
<a href="Subject?Tag=
#Html.DisplayFor(model =>item.Etiket)">
#item.Etiket.Split(',').ToString()</a>
</p>
<div class="image-section">
<img src="#Html.DisplayFor(model => item.Resim)"
alt="image post" height="206" width="498" />
</div>
<p>
<a class="more" href="Subject?SubjectId==
#Html.DisplayFor(model => item.Id)">Devamı »</a>
</p>
}
</div>
I want to split under side for (',')
#item.Etiket.Split(',').ToString()
When i run program , i see this code..
System.String[] in stead of Etiket
I tried to solve this with foreach Etiket.Split but id did not work .
How can i solve this problem in View?
<a href="Subject?Tag=
#Html.DisplayFor(model =>item.Etiket)">
#item.Etiket.Split(',').ToString()</a>
it should be like following as you said in your comment
<a href="Subject?Tag=
#Html.DisplayFor(model =>item.Etiket)">
#foreach(var x in item.Etiket.Split(','))
{
#x
}
</a>
String.Split: Returns a string array that contains the substrings in this string that are delimited by elements of a specified string array.
So what you are getting is correct output as per code.
You can try to display first element of substring
#item.Etiket.Split(',')[0]

Change method call order when form is posted in MVC

a bit of a strange one here. I've got a blog that's another 'dip my toe into MVC' project that will highlight the benefits of our new Intranet. I have a typical blog post page with the article, comments and a form to submit your comments against a given article.
I have a stringly typed main View ("Post") which has the article content, then two Html.RenderAction methods; one to get the comments and one to add comments via a form.
My issue is that when a comment is posted, my GetComments method is called before AddComment, so when the page is refreshed the new comment isn't visible although it has been added to the database. A quick F5 confirms this. I understand that GetComments is being called first due to it being declared first in the view but I'm not sure how to tell the view to do an add before a get.
Here's my code:
Controller:
public ActionResult AddComment()
{
return PartialView("AddComment");
}
[HttpPost]
public ActionResult AddComment(Comment comment)
{
comment.DateSubmitted = DateTime.Now;
db.Comments.Add(comment);
db.SaveChanges();
return PartialView(comment);
}
public ActionResult GetComments(int articleid)
{
var comments = db.Comments.Where(c => c.ArticleID == articleid).ToList();
return PartialView(comments);
}
Post view
#model IntranetBlog.Models.Article
#{
ViewBag.Title = "Post";
}
<div class="row">
<div class="span12">
<h3>#Html.DisplayFor(modelItem => Model.Title)</h3>
<small>by Ruth Barlow on #Html.DisplayFor(modelItem => Model.DateCreated)</small>
#if (Model.Image != null)
{
<p>
<img src="#Url.Action("GetImage", "Home", new { articleID = Model.ArticleID })" alt="" width="150" height="150" />
</p>
}
<div>
#Html.DisplayFor(modelItem => Model.Body)
</div>
<small>Posted under #Html.DisplayFor(modelItem => Model.Category.Name)</small>
</div>
<div class="span12">
#{
Html.RenderAction("GetComments", "Home", new { articleID = Model.ArticleID });
}
</div>
<div class="span12">
#{
Html.RenderAction("AddComment", "Home", new { articleID = Model.ArticleID });
}
</div>
</div>
GetComments partial:
#model IEnumerable<IntranetBlog.Models.Comment>
#if (Model.Any())
{
<h3>What you're saying</h3>
foreach (var item in Model)
{
<div>
Comment: #Html.DisplayFor(modelItem => item.Body)
</div>
<div>
Submitted by: #Html.DisplayFor(modelItem => item.SubmittedBy)
on #Html.DisplayFor(modelItem => item.DateSubmitted)
</div>
<hr />
}
}
else
{
<p>There are no comments for this post. Why not add one?</p>
}
AddComment partial
#model IntranetBlog.Models.Comment
#using (Html.BeginForm())
{
<h3>Why not leave us a comment?</h3>
#Html.ValidationSummary()
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Body, 20, 20, null)
#Html.ValidationMessageFor(model => model.Body)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SubmittedBy)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SubmittedBy)
#Html.ValidationMessageFor(model => model.SubmittedBy)
</div>
<p>
<input type="submit" value="Add comment" id="AddComment" class="btn btn- primary" />
</p>
</fieldset>
}
Hope this makes sense.
Thanks in advance.
The trick is to use Html.Action instead of Html.RenderAction this will allow you to store the result in a variable and then add it to the display where it is needed.
This will allow you to generate the PartialView in the logical order you need, while displaying them in an other order.
See this post for a quick example on how to do it : https://stackoverflow.com/a/13301057/971693
I would suggest to you a slightly different approach. Instead of using Html.BeginForm, think about using Ajax.BeginForm to submit the comment. Being ajax, it will have better performance as it allows your method to just return the comments so you can replace the old ones, or even just the newly added one so it can be added to the bottom of the list. Having said that, this solution does rely on the use of javascript and preferably jquery-unobtrusive-ajax to work and render decent looking client code. You don't have to know javascript to use this method thanks to the AjaxOptions class which has some powerful yet easy to use options built into it.

Delete and Update List of Objects in Asp.Net MVC 4

I have a form that has an input section at the top of the page and in the bottom half it displays a list of the objects that were added. I need to be able to Edit and Delete these objects and I'm not sure where to start or how to do it.
This code display the list of objects.
#if (Model.ListOfRecipients != null)
{
for (int i = 0; i < Model.ListOfRecipients.Count; i++)
{
<div class='recipient-wrapper'>
<div class='decision_block'>
<table class='recipient'>
<tr>
<td class='recipient-title'>
#Html.HiddenFor(model=>model.ListOfRecipients[i].RecipientId)
<h3>
#Html.DisplayTextFor(model => model.ListOfRecipients[i].RecipientName)
#Html.HiddenFor(model => model.ListOfRecipients[i].RecipientName)
</h3>
<div class='delivery-type'>
Delivery Type: #Html.DisplayTextFor(model => model.ListOfRecipients[i].DeliveryType)
#Html.HiddenFor(model => model.ListOfRecipients[i].DeliveryType)
</div>
</td>
<td class='na express'>
#Html.CheckBoxFor(model => model.ListOfRecipients[i].ExpressIndicator)
#Html.HiddenFor(model => model.ListOfRecipients[i].ExpressIndicator)
</td>
<td class='quantity'>
<h3>
Qty #Html.DisplayTextFor(model => model.ListOfRecipients[i].Quantity)
#Html.HiddenFor(model => model.ListOfRecipients[i].Quantity)
</h3>
</td>
<td class='action'>
<input class='button edit_recipient' type='button' value='Edit' />
<input class='button delete_recipient' type='button' value='Delete' />
</td>
</tr>
</table>
<input class='button update_recipient' type='button' value='Update' />
<a class='cancel_update' href='#'>Cancel</a>
</div>
</div>
</div>
}
}
You need to write Edit and Delete action methods in your controller and then set your two buttons to call the appropriate method.
The code for the action methods will depend on several factors that may to broad to address here.
Using Razor Syntax -- sorry the others were using wrong markup:(
<input class='button edit_recipient' type='button' value='Edit'
onclick="location.href='#Url.Action("Edit", "Controller", new { id = Model.Id } )'" />
You could create a delete controller and an edit controller and in the above view have a beside each one that has a delete and edit which recieves the objects id and each button goes to it's own view where they can edit or delete

Resources