How to use RadioButton to render View - asp.net-mvc

I have a controller as shown below.
public ActionResult Index()
{
return View(db.FEE_TYPES.ToList());
}
By default it will render a View called Index. However, I have three views I want to Render
Index
Index2
Index3
I want to have three RadioButtons on the View
RadioButton1
RadioButton2
RadioButton3
When RadioButton1 is clicked, Render Index.
When RadioButton2 is clicked, Render Index2
When RadioButton3 is clicked, Render Index3
Please how do I achieve this?

I have Created a Demo from your Code Reference.
First i have create a Model with 3 properties in it.
Model
public class DemoModel
{
public string Radio1 { get; set; }
public string Radio2 { get; set; }
public string Radio3 { get; set; }
}
After creating a Model i have created a Controller with name RadioRenderController in that controller i have added 4 Action Method in that Index returns Main View.
And Remaining 3 Action Methods [ GetView1 , GetView2 , GetView3 ] return partial View.
Controller
using System.Web.Mvc;
using WebApplication6.Models;
namespace WebApplication6.Controllers
{
public class RadioRenderController : Controller
{
// GET: RadioRender
public ActionResult Index()
{
DemoModel DemoModel = new Models.DemoModel();
return View(DemoModel);
}
public ActionResult GetView1()
{
return PartialView("_DemoView1");
}
public ActionResult GetView2()
{
return PartialView("_DemoView2");
}
public ActionResult GetView3()
{
return PartialView("_DemoView3");
}
}
}
View
#model WebApplication6.Models.DemoModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function GetView1() {
$("#viewPlaceHolder").load("/RadioRender/GetView1");
}
function GetView2() {
$("#viewPlaceHolder").load("/RadioRender/GetView2");
}
function GetView3() {
$("#viewPlaceHolder").load("/RadioRender/GetView3");
}
</script>
</head>
<body>
<div>
#Html.RadioButtonFor(m => m.Radio1, "1", new { #onclick = "GetView1();" }) Radio1
</div>
<div>
#Html.RadioButtonFor(m => m.Radio1, "2", new { #onclick = "GetView2();" }) Radio2
</div>
<div>
#Html.RadioButtonFor(m => m.Radio1, "3", new { #onclick = "GetView3();" }) Radio3
</div>
<div id="viewPlaceHolder"></div>
</body>
</html>
Partial Views
Output

Related

Model returning null from a View with multiple models

I have two models, LoginModel and DatabaseModel. Combining them, I have created DatabaseCombinedWithOtherModel. The View, Login.cshtml is Strongly-Typed with the combined model. On running the Login.cshtml, the LoginModel returns null
I have all the necessary get and set methods
Here is the Controller class
namespace ReadingCat.Controllers
{
public class LoginController : Controller
{
private int userid;
// GET: Login
[HttpGet]
public ActionResult Login()
{
return View(new DatabaseCombinedWithOtherModel());
}
[HttpPost]
public ActionResult Login(DatabaseCombinedWithOtherModel model)
{
string realPassword = "";
string paswordFromUser = "";
string query = "SELECT password, userid FROM USERS WHERE username
= '" + model.loginModel.username + "'";
DataSet dataSet = model.databaseModel.selectFunction(query);
if (realPassword == paswordFromUser)
{
userid =
Convert.ToInt32(dataSet.Tables[0].Rows[0].ItemArray[1]);
model.loginModel.userid = userid;
return View("~/Views/Profile/Profile.cshtml",
model.loginModel);
}
else
return View();
}
}
}
Here is the Model:
namespace ReadingCat.Models
{
public class DatabaseCombinedWithOtherModel
{
public DatabaseModel databaseModel { get; set; }
public LoginModel loginModel { get; set; }
}
}
And here is the View:
#model ReadingCat.Models.DatabaseCombinedWithOtherModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<!-- Main css -->
<link rel="stylesheet" href="~/css/login.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form">
</form>
#using (Html.BeginForm("Login", "Login", FormMethod.Post))
{
<form class="login-form">
#Html.TextBox("Username", null, new { placeholder = "Username",
#class = "login.css" })
#Html.ValidationMessageFor(model => model.loginModel.username);
#Html.Password("Password", null, new { placeholder = "Password",
#class = "login.css" })
#Html.ValidationMessageFor(model => model.loginModel.password);
<div class="form-submit">
<button type="submit" value="Submit" class="submit"
id="submit" name="submit">Login</button>
</div>
<p class="message">Not registered? Create an account</p>
</form>
}
</div>
</div>
<img class="coffee-image" src="~/images/coffee.gif" alt="">
It is giving the following error
System.NullReferenceException: 'Object reference not set to an instance
of
an object.'
ReadingCat.Models.DatabaseCombinedWithOtherModel.loginModel.get returned
null.
I think this error about not fully declare DatabaseCombinedWithOtherModelthis model.
Please try this code.
private int userid
DatabaseCombinedWithOtherModel modelobj = new DatabaseCombinedWithOtherModel();
// GET: Login
[HttpGet]
public ActionResult Login()
{
return View(modelobj);
}
And also try this thing that before call the model in view firstly add some
values in objects from controller side pass return View(modelobj);and then call in view side.
Since you are not seting the loginmodel, it will be null Which will throw the exception.
Either initialize the loginModel in the otherModel's constructor or in the Login get action.
Try
namespace ReadingCat.Models
{
public class DatabaseCombinedWithOtherModel
{
public DatabaseModel databaseModel { get; set; }
public LoginModel loginModel { get; set; }
}
public DatabaseCombinedWithOtherModel()
{
loginModel = new LoginModel();
databaseModel = new DatabaseModel();
}
}
or
[HttpGet]
public ActionResult Login()
{
var vm = new DatabaseCombinedWithOtherModel()
vm.loginModel = new LoginModel();
vm.databaseModel = new DatabaseModel();
return View(vm);
}
The mentioned error goes away if #Html.Textbox is replaced with #Html.EditorFor. Then, another error arises with the DatabaseModel. It returns null. So I created a different object of DatabaseModel and worked with that.

Pass value in asp.net mvc

I am trying to pass data of method to another method. Can you help me please?
Here is my code: return View(model); model should be pass public ActionResult ShowData(Student model) method.
public ActionResult ShowData(int? ID)
{
var model = new StudentModel
{
StudentData = stdDef
};
return View(model);
}
[HttpPost]
public ActionResult ShowData(Student model) {
This is how it is done. Please pay attention to my comments in the code:
Controller/Model:
public class StudentModel
{
public string StudentData { get; set; }
}
public class HomeController : Controller
{
public string PassDataToMe(StudentModel model)
{
return model.StudentData;//no view defined
}
public ActionResult ShowData(int? ID)
{
var stdDef = "stdDef";
var model = new StudentModel
{
StudentData = stdDef
};
return View(model);
}
[HttpPost]
//!changed this to studentmodel
public ActionResult ShowData(StudentModel model)
{
//this is how you pass limited bytes of data that are not encrypted
return RedirectToAction("PassDataToMe", model);
}
View:
#model Testy20161006.Controllers.StudentModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowData</title>
</head>
<body>
<div>
#using (Html.BeginForm())
{
#Html.LabelFor(r => r.StudentData);
#Html.TextBoxFor(r=>r.StudentData);
<input type="submit" value="submit" />
}
</div>
</body>
</html>

Post from MVC view don't get bind to controller model

I have a partial view which is displayed on modal window:
public ActionResult Details(string test)
{
var model = _taskService.GetDocumentTasks(test);
return PartialView("_Details", new CustomViewModel { TaskList = model.ToList() });
}
public class CustomViewModel
{
public DocumentStatus Status { get; set; }
public IList<DocumentTask> TaskList { get; set; }
}
I am able to loop TaskList in the view and draw form fields like this:
#model CustomViewModel
#using (Html.BeginForm())
{
#for (int i = 0; i < Model.TaskList.Count(); i++)
{
#Html.HiddenFor(m => m.TaskList[i].TaskId)
<div class="col-sm-6 col-md-4">
<img src="#Html.EditorFor(m => m.TaskList[i].DocumentPath)">
.. other form items here
</div>
}
<input class="btn btn-primary" type="submit" value="Save" />
}
This displays the form fields but when I click the submit button the modal which is sent to the controller is null. I have tried a few different ways of binding it but no success. The model on on the below controller is always null. Any idea how to bind the submitted form details to controller model?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(CustomViewModel model)
{
}
Thanks.
This will work. I made some minor changes, so please follow this:
Controller/Model:
public class HomeController : Controller
{
public class TaskService
{
public Collection<DocumentTask> GetDocumentTasks(string test)
{
Collection<DocumentTask> aCollection = new Collection<DocumentTask>();
var documentTaska = new DocumentTask { TaskId = "patha", DocumentPath = "~/Images/w.JPG" };
var documentTaskb = new DocumentTask { TaskId = "pathb", DocumentPath = "~/Images/w.JPG" };
var documentTaskc = new DocumentTask { TaskId = "pathc", DocumentPath = "~/Images/w.JPG" };
var documentTaskd = new DocumentTask { TaskId = "pathd", DocumentPath = "~/Images/w.JPG" };
aCollection.Add(documentTaska);
aCollection.Add(documentTaskb);
aCollection.Add(documentTaskc);
aCollection.Add(documentTaskd);
return aCollection;
}
}
public class DocumentStatus { }
public class DocumentTask
{
public string TaskId { get; set; }
public string DocumentPath { get; set; }
public string UserDataToProveItWorking { get; set; }
}
public class CustomViewModel
{
public DocumentStatus Status { get; set; }
public IList<DocumentTask> TaskList { get; set; }
}
TaskService _taskService = new TaskService();
public ActionResult Overview()
{
return View();
}
public ActionResult Details(string test)
{
var model = _taskService.GetDocumentTasks(test);
return PartialView("_Details", new CustomViewModel { TaskList = model.ToList() });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(CustomViewModel model)
{
return View("Overview");
}
View Overview.cshtml:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Overview</title>
</head>
<body>
<div>
#Html.ActionLink("GetPartialView", "Details", new { test = "aTestValue"})
</div>
</body>
</html>
Partial View _Detials.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Overview</title>
</head>
<body>
<div>
#Html.ActionLink("GetPartialView", "Details", new { test = "aTestValue"})
</div>
</body>
</html>

Scaffold Create and Edit Views with Dropdownlist in MVC

I have a MVC3 application that populates a dropdownlist from a Model. When I select an item from the list , i would like to Update the url ('/Edit/4') on a single 'edit' link which will allow me display the edit view, i.e rather than use a template which creates edit links for all records in the model, I would like to use one edit link and then update it as items are selected in the dropdownlist. I have been able to achieve some of this using jquery , I would like to do it in C# code using MVC.
Any thoughts??
I created a Sample code. I have an area. Highlighted part is your concerned code.
Controller
public class DropdownController : Controller
{
[HttpGet]
public ActionResult DropDownListFor()
{
Practise.Areas.MyPractise.Models.Dropdown d = new Models.Dropdown();
return View(d);
}
public ActionResult Edit(string Val)
{
return View();
}
}
Model
public class Dropdown
{
[Required(ErrorMessage = "Please select state")]
public string StateId { get; set; }
public int MyProperty { get; set; }
public List<SelectListItem> States
{
get
{
return new List<SelectListItem>()
{
new SelectListItem
{
Text = "Punjab",
Value = "Pb",
Selected = false
},
new SelectListItem
{
Selected = false,
Value = "HM",
Text = "Himachal"
}
};
}
}
}
DropDownListFor View
#model Practise.Areas.MyPractise.Models.Dropdown
<!DOCTYPE html>
<html>
<head>
<title>DropDownListFor</title>
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#StateId').change(function () {
if($('#StateId option:selected').val() == "")
$('.edit').attr('href', "#");
else
$('.edit').attr('href',
"#Url.Action("Edit", "Dropdown",
new RouteValueDictionary(new { area = "MyPractise" }))"
+ "/" + $('#StateId option:selected').text());
});
});
</script>
</head>
<body>
#using (Html.BeginForm("DropDownListFor", "DropDown", FormMethod.Post,
new { id = "DropDownList" }))
{
#Html.DropDownListFor(m => m.StateId, Model.States, "select");
#Html.ValidationMessageFor(m => m.StateId);
<a class="edit" href="#">Edit</a>
<input type="submit" name="Submit" value="Submit" />
}
</body>
</html>
Area registration under MyPractiseAreaRegistration class under highlighted area
public class MyPractiseAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "MyPractise";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"MyPractise_default1",
"MyPractise/{controller}/{action}/{Val}",
new { action = "Index", Val = UrlParameter.Optional }
);
context.MapRoute(
"MyPractise_default",
"MyPractise/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}

asp.net 4.0 MVC 3 ajax form in Overlay

I am interested in creating an AJAX form submit in a jQuery overlay. I am not sure how to approach this, do I just toss a partial view into the overlay?
I want to pass to the server the data in the form of a model so I can save it the the data base, I need to be able to create some sort of indication as to whether or not the request succeed. Can anyone guide me through this?
I am kinda new with AJax.
You could use jQuery UI Dialog. For example let's suppose that you have a view model:
public class MyViewModel
{
public string Foo { get; set; }
[Required]
public string Bar { get; set; }
}
and a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Modal()
{
return PartialView(new MyViewModel());
}
[HttpPost]
public ActionResult Modal(MyViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView(model);
}
return Json(new { success = true });
}
}
In this example the Index action will serve the main view which will simply contain a link allowing to show the form as a modal dialog.
Here's the Index.cshtml view:
#Ajax.ActionLink(
"show form in modal",
"modal",
new AjaxOptions { OnSuccess = "onModalLoad" }
)
<div id="modal"></div>
and the Modal.cshtml partial which will contain the form:
#model MyViewModel
#using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "onSubmitSuccess" }))
{
<div>
#Html.LabelFor(x => x.Foo)
#Html.EditorFor(x => x.Foo)
#Html.ValidationMessageFor(x => x.Foo)
</div>
<div>
#Html.LabelFor(x => x.Bar)
#Html.EditorFor(x => x.Bar)
#Html.ValidationMessageFor(x => x.Bar)
</div>
<button type="submit">OK</button>
}
The last step is to wire everything using javascript. Here are the 2 callbacks used:
var onModalLoad = function (result) {
$('#modal').html(result).dialog();
}
var onSubmitSuccess = function (result) {
if (!result.success) {
$('#modal').html(result);
} else {
alert('thanks for submitting');
$('#modal').dialog('close');
}
};
and that's it.
Don't forget to reference the jquery-ui and jquery.unobtrusive-ajax scripts to your page:
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Resources