ASP.NET RAZOR cannot capture the event - asp.net

I want to get the value from the selected radio button after a user clicked on one of them and display it at the bottom, but it doesn't work.
I do not want to use JAVASCRIPT and MVC.
Please help~~~
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Contact";
var selectedValue = "Male selected";
}
#{
if (IsPost)
{
selectedValue = Request["Gender"].ToString();
}
}
<div>
<table>
<tr>
<td>
#Html.RadioButton("Gender", "Male", true) Male
</td>
<td>
#Html.RadioButton("Gender", "Female", false) Female
</td>
</tr>
</table>
<b>#selectedValue</b>
</div>

If you don't want to use JavaScript, you will need a roundtrip to the server. Razor is not executed on the client. In fact the client never even sees the razor code in the first place.

Related

View returning empty model to Controller

I'm current working on making a sort of wiki of plants. The first thing we started doing is the managment of the users in the site. For that we made this view that shows the results of a search from the database. The search works fine and the ViewData["datos"] returns what it should, and in this table we show the users (From the Model Usuario). In the end, for each user it should show a button that sends the Model for that user to another Controller. The problem is that the Controller receives an empty model.
Here's the code for the View. The input with the value Editar is the one that should send the model.
#model AtlasPlantasMedicinales.Models.Usuario
#{
ViewBag.Title = "Tabla";
}
#if (ViewData["datos"]!=null){
<table>
#foreach (var elemento in (List<AtlasPlantasMedicinales.Models.Usuario>)(ViewData["datos"]))
{
<tr>
<td>
#elemento.Nombre
</td>
<td>
#elemento.Carrera
</td>
<td>
#elemento.Institucion
</td>
<td>
#elemento.usuario
</td>
<td>
#elemento.correo
</td>
#using (Html.BeginForm("FormularioEditar", "Usuario", FormMethod.Post))
{
<td>#Html.HiddenFor(m => elemento) <input type="submit" value="Editar"></td>
}
</tr>
}
</table>
}
How can we send the model in elemento to the controller?
We have also tried making a Html.HiddenFor for each attribute in the model, but it still doesn't work.
Please keep in mind that me (and my teammmates) are completely new at ASP.NET MVC 4
This is a model binding problem. If you are willing to use the default model binder, use for loop instead of foreach. Your code will go something as as follows (Since you didn't post the Model/ViewModel, I will use ModelId as the property, and usuario as the value):
#for (int i = 0; i < (List<AtlasPlantasMedicinales.Models.Usuario>)(ViewData["datos"])).Count(); i++)
{
var elemento = (List<AtlasPlantasMedicinales.Models.Usuario>)(ViewData["datos"])).ElementAt(i);
<tr>
<td>
#elemento.Nombre
</td>
<td>
#elemento.Carrera
</td>
<td>
#elemento.Institucion
</td>
<td>
#elemento.usuario
</td>
<td>
#elemento.correo
</td>
#using (Html.BeginForm("FormularioEditar", "Usuario", FormMethod.Post))
{
<td>#Html.HiddenFor(m => m.ModelId, new { #Value = elemento.usuario }) <input type="submit" value="Editar"></td>
}
</tr>
}
Now, in the controller you will receive Usuario model with only the ModelId property initialized.
For more information about the model binding, I recommend you to this read this blog post by Scott Hanslman

How to use Hidden fields in HTML5 asp.net mvc 4?

I am working on a MVC 4 asp.net application(vb.net project)
<table>
<tr><td>Billable item</td><td>#Html.DropDownList("RteBillableItem") </td><td>Quantity</td><td>#Html.TextBox("Quantity")</td></tr>
<tr><td>Doctor Fee</td><td>#Html.TextBox("DoctorFee")</td><td>Hospital Fee</td>
<td>#Html.TextBox("HospitalFee")</td></tr>
<tr><td></td><td></td><td></td><td><input type="submit" id="AddItem" value="Add Item" /></td></tr>
</table>
As seen in the image, i will be selecting an item from the drop down list, enter some data in the text boxes, and click on the button "Add Item", the form will do a post back.
The code in post back controller is :
HttpPost()
Function Index(ByVal Collection As FormCollection, ByVal Hidden As HiddenField) As ActionResult
Dim Test As New TestModel
Test.Update(CodeFactory(item), CInt(Collection("Quantity")),CInt(Collection("DoctorFee")), CInt(Collection("HospitalFee")))
//This will add the Item in a dictionary which i have used in my ModelTest
Return View(Test)
End Function
After adding the Item into my dictionary, i will send this model to "View", where i have to list the values in a table, picking the values from Dictionary of TestModel. The code for listing the values in View is:
#For Each item In Model
Dim currentItem = item
#<tr>
<td>
#Html.DisplayFor(Function(modelItem) currentItem.BillableItemId)
</td>
<td>
#Html.DisplayFor(Function(modelItem) currentItem.BillableItemName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", New With {.id = currentItem.OpBillId}) |
#Html.ActionLink("Details", "Details", New With {.id = currentItem.OpBillId}) |
#Html.ActionLink("Delete", "Delete", New With {.id = currentItem.OpBillId})
</td>
</tr>
next
</table>
But the thing is , whenever i do a post back, all the previous data which i have added in the dictionary of TestModel is lost. I know that i am re-initializing my Test object of the model, TestModel.
I think i have to use Hidden fields, to retain the old data of TestModel, even after PostBack.
But i do not know how to do it, please give your valuable suggestions.

Code still loads content on new page

Hi I have problem with my MVC application.
I would like click on ActionLink > load data from server > and insert data to div in same page.
But my code still loads content on new page and I don`t have idea why. Anybody to help me ?
This is my Index.cshtml in HomeController,
#model IEnumerable<Kango_kmen.KangoKmenWS.WSEntityInfo>
#Content.Script("jquery-1.9.1.min.js", Url)
#Content.Script("jquery.unobtrusive-ajax.min.js",Url)
#Content.Script("jquery.unobtrusive-ajax.js",Url)
#Content.Script("myScript.js",Url)
#section Entities{
<table>
<tr>
<th>
<input type="submit" value="zobrazit" />
</th>
<th>
iD
</th>
<th>
name
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Ajax.ActionLink("..", "CheckEntity", new { id = item.iD },
new AjaxOptions{ UpdateTargetId="properties",
HttpMethod="GET",
InsertionMode=InsertionMode.InsertAfter,
})
</td>
<td>
#Html.DisplayFor(modelItem => item.iD)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
</tr>
<tr>
<td>
<div id="properties">
</div>
</td>
</tr>
}
</table>
}
#section PropertyInfo{
<p>Property info</p>
}
#section Properties{
<p>properties</p>
}
And here is my Controller in HomeController
public PartialViewResult CheckEntity(int id)
{
var model = WSConnect.getEntityInfo(id);
if(model !=null){
return PartialView("CheckEntity", model.property);
}
var modell = new WSEntityInfo[0];
return PartialView("CheckEntity", modell);
}
and ChecktEntity is the Partial view but everytime I click on ActionLink controller load url: /Home/ChceckEntity/1000 for exmaple on view data on this new page "(
There are 2 things wrong with your code:
You have included the jquery.unobtrusive-ajax.js script twice, once the minified version and once the standard version. You should include it only once
The jquery.unobtrusive-ajax.js is not compatible with jquery 1.9.1 because one of the breaking changes in jQuery 1.9 is that the .live() method was removed and the jquery.unobtrusive-ajax.js script relies on it. If you look at your javascript console you would see the following error: The .live method is undefined.. So if you want to use the unobtrusive AJAX functionality in ASP.NET MVC you will have to downgrade the version of jQuery. For example the 1.8.3 version should be fine.
So:
#model IEnumerable<Kango_kmen.KangoKmenWS.WSEntityInfo>
#Content.Script("jquery-1.8.3.min.js", Url)
#Content.Script("jquery.unobtrusive-ajax.min.js", Url)
#Content.Script("myScript.js", Url)
Also please learn how to debug your javascript code. Use a tool such as FireBug or Chrome developer toolbar where all those errors will be shown.

asp.net mvc 3, dynamic array

I am a beginner in ASP.Net MVC 3
I will make a dynamic array initially must show me the first ten elements, and when I click view more displays all array elements
here's what I did:
<table>
#foreach (var tweet in Model)
{
<tr>
<td>
<img alt="" src="#tweet.ProfileImageUrl" />
<br />
<input id="rowIDs" type="checkbox" />
</td>
<td>
<strong>#tweet.Name</strong>
<br />
Friends: <strong>#tweet.FriendsCount</strong>
</td>
</tr>
}
</table>
thank you in advance
You have to put 10 items in the controller,
return View(array.Take(10).Skip(page));
Do not use the button anymore. Use the pager.
You need to peredovat variable Pag.
The easiest way(on my opinion) is to create a anchor to the page, itself, with a query string.
Your View must have an anchor like this:
All Comments
And relative controller(HttpGet, not HttpPost(if it has any)) must be something like this:
public ViewResult List(bool fullComment=false)
{
if (fullComment)
return View(dbContext.EntityList.ToList());
else
return View(dbContext.EntityList.Take(5).ToList());
}
Note: if the page has querystring already, in creating anchor link, in view, you must pay attention to this.

ASP.Net MVC EditorFor not working

I am trying to render a table, using EditorFor, and a partialview, I think.
I have a model with a List<> property defined like this:
public List<TransactionSplitLine> TransactionSplitLines { get; set; }
The idea is that a user selects a few drop downs and enters a value into an edit box, and clicks a button. The model goes back to the controller, and the controller adds the entered values to the List<>
[HttpPost]
public ActionResult AccountTransaction(AccountTransactionView model)
{
var reply = CreateModel(model);
if (model.CategoryIds != null)
{
foreach (var c in model.CategoryIds)
{
reply.TransactionSplitLines.Add(new TransactionSplitLine { Amount = "100", Category = "Test Category", SubCategory = "Test More", CategoryId = int.Parse(c) });
}
}
reply.TransactionSplitLines.Add(new TransactionSplitLine { Amount = "100", Category = "Test Category", SubCategory = "Test More", CategoryId = 1 });
return View("AccountTransaction", reply);
}
Ignore the CreateModel. It simply sets up some data. Also, I am hardcoding data. This will eventually come from some form values.
The model is then returned to the same screen, allowing the user to ender more data. Any items in the List<> are read and a Table is rendered. I also have to store the current listen item values in hidden fields, so that they can be submitted back, along with the new data entered, so that the list can grow each time the user adds data.
The view is defined like this:
<table width="600">
<thead>
<tr class="headerRow">
<td>
Category
</td>
<td>
Sub Category
</td>
<td>
Amount
</td>
</tr>
</thead>
<tbody>
<%=Html.EditorFor(m=>m.TransactionSplitLines) %>
</tbody>
</table>
This is my first attempt with EditorFor...
My View is in a folder 'Views/BankAccount/AccountTransaction.aspx
I have created a ascx in Views/Shared/TransactionSplitLines.ascx
The code for the ascx is like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BudgieMoneySite.Models.TransactionSplitLine>" %>
<tr>
<td>
<%=Model.Category %>
<%=Html.HiddenFor(x => x.CategoryId)%>
</td>
<td>
<%=Model.SubCategory %>
<%=Html.HiddenFor(x => x.SubCategoryId)%>
</td>
<td>
<%=Model.Amount %>
<%=Html.HiddenFor(x => x.AmountValue)%>
</td>
</tr>
This is data
The 'This is data' is just test stuff, which is never rendered.
When I run this, all that happens is that my output is rendered as:
<table width="600">
<thead>
<tr class="headerRow">
<td>
Category
</td>
<td>
Sub Category
</td>
<td>
Amount
</td>
</tr>
</thead>
<tbody>
Test Category
</tbody>
</table>
It seems like the ascx isn't being used? I'd expect to see the 'This is data' text. But, nothing. Hopefully you can see an obvious fault?
Your editor template should be either:
~/Views/Shared/EditorTemplates/TransactionSplitLine.ascx
or:
~/Views/BankAccount/EditorTemplates/TransactionSplitLine.ascx
The name of the ascx is always the type name of the collection item (TransactionSplitLine and not TransactionSplitLines) and it should be situated at ~/Views/Shared/EditorTemplates or ~Views/ControllerName/EditorTemplates.
Or if you want to use a custom editor template name:
<%= Html.EditorFor(m=>m.TransactionSplitLines, "~/Views/foo.ascx") %>
Or use UIHintAttribute on your model.

Resources